Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 61 ยท Practice and Review

Practice: Basics and Control Flow

Seven Dart exercises with solutions on variables, strings, null safety, loops, switch expressions and patterns. Try each one first, then compare with the answer.

Reading about a language is not the same as writing it. This lesson gives you seven small exercises that cover the first half of the tutorial: variables and numbers, strings, null safety, loops, and if and switch. Each exercise has a task, a hint and a collapsed solution. Every solution is real Dart, shown read-only, and the TryIt blocks run the same logic as TypeScript stand-ins so you can see the expected output.

The exercises are deliberately small: each fits in under fifteen lines. The goal is to build the habit of turning a sentence into code, not to solve puzzles.

How to practice

The loop that works best is simple. Read the task, predict what the output should look like, write your own version, run it, and only then open the solution. If you want to run real Dart, paste your code into DartPad, or use dart run on your machine. If you get stuck for more than ten minutes, read the hint, then the solution, and close it and write the code again from memory. Copying is not practice; retyping from memory is.

flowchart LR
    A["Read the task"] --> B["Predict the output"]
    B --> C["Write your solution"]
    C --> D["Run it"]
    D --> E{"Matches?"}
    E -->|"yes"| F["Read the model solution<br/>and compare style"]
    E -->|"no"| G["Read the hint,<br/>fix and rerun"]
    G --> D

Predict first, then run. Comparing your style with the model solution is the last step, not the first.

Each Dart solution below uses a main function or a small helper function. Remember that Dart programs start at main, strings use interpolation with $name or ${expression}, and ~/ is integer division (see Numbers).

Exercise 1: a temperature table

Task. Print a table of Celsius values from -10 to 40 in steps of 10, next to their Fahrenheit values with one decimal place. The formula is f = c * 9 / 5 + 32. Right-align both columns so the numbers line up.

Hint. Use a for loop with c += 10. toStringAsFixed(1) formats a double, and padLeft(width) aligns text to the right (see Strings).

Show the solution
DART
void main() {
  for (var c = -10; c <= 40; c += 10) {
    final f = c * 9 / 5 + 32;          // `/` always gives a double
    final left = c.toString().padLeft(4);
    final right = f.toStringAsFixed(1).padLeft(6);
    print('$left C = $right F');
  }
}

The division operator / always produces a double, even for two int operands, so no cast is needed. The loop variable is a var that Dart infers as int.

Exercise 2: FizzBuzz with a switch expression

Task. Write String fizzBuzz(int n). It returns 'FizzBuzz' when n is divisible by both 3 and 5, 'Fizz' when divisible by 3, 'Buzz' when divisible by 5, and otherwise the number as text. Print the results for 1 to 15.

Hint. Match on a record of the two remainders: (n % 3, n % 5). A pattern like (0, _) means "first is zero, second can be anything" (see switch expressions).

Show the solution
DART
String fizzBuzz(int n) => switch ((n % 3, n % 5)) {
      (0, 0) => 'FizzBuzz',
      (0, _) => 'Fizz',
      (_, 0) => 'Buzz',
      _ => '$n',
    };

void main() {
  for (var i = 1; i <= 15; i++) {
    print(fizzBuzz(i));
  }
}

Order matters: the first matching case wins, so the (0, 0) case must come before the two single cases. The final _ is the catch-all that makes the switch exhaustive.

Exercise 3: leap years

Task. Write bool isLeapYear(int year). A year is a leap year when it is divisible by 4, except that years divisible by 100 are not leap years unless they are also divisible by 400. Test it with 1900, 2000, 2024 and 2100.

Hint. One boolean expression with &&, || and % is enough (see Booleans and Operators).

Show the solution
DART
bool isLeapYear(int year) =>
    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;

void main() {
  for (final y in [1900, 2000, 2024, 2100]) {
    print('$y: ${isLeapYear(y)}');
  }
}

The parentheses are not required (&& binds tighter than ||) but they show the intent. Names that start with is are the Dart convention for boolean functions.

Run the stand-in below to see the expected output of the first three exercises. Try rewriting each function yourself before you read the code, and add a few inputs of your own:

TypeScript Exercises 1 to 3 (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Exercise 4: a null-safe greeting

Task. Write String greet(String? name). If name is null, empty, or only spaces, return 'Hello, stranger!'. Otherwise return 'Hello, <trimmed name>!'. The function must not use the ! operator.

Hint. Compute the trimmed value with ?., then test it for null and emptiness. After the check, Dart promotes the local variable to a non-nullable String (see Null Safety).

Show the solution
DART
String greet(String? name) {
  final trimmed = name?.trim();
  if (trimmed == null || trimmed.isEmpty) {
    return 'Hello, stranger!';
  }
  return 'Hello, $trimmed!';   // trimmed is a plain String here
}

A shorter variant uses ??: final clean = name?.trim() ?? ''; and then a single isEmpty check. Either is fine. The point is to avoid name!, which would crash on null instead of handling it. Promotion works because trimmed is a local final; it would not work on a mutable field, because another piece of code could change it between the check and the use.

Exercise 5: sum the digits

Task. Write int digitSum(int n) that adds the digits of n, ignoring the sign: digitSum(4821) is 15 and digitSum(-90) is 9. Use a loop, not string conversion.

Hint. n % 10 is the last digit and n ~/ 10 removes it. Stop when nothing is left.

Show the solution
DART
int digitSum(int n) {
  var rest = n.abs();
  var sum = 0;
  while (rest > 0) {
    sum += rest % 10;
    rest ~/= 10;      // integer division, then assign
  }
  return sum;
}

~/= is the compound assignment form of the truncating division operator. For 0 the loop body never runs and the result is 0, which is correct.

Exercise 6: primes with a labeled continue

Task. Collect all prime numbers up to 30 into a list and print it. A number is prime if it has no divisor between 2 and its square root.

Hint. An inner loop tries divisors. When one divides evenly, you want to jump to the next candidate in the outer loop. A label on the outer loop lets continue target it (see Loops).

Show the solution
DART
void main() {
  final primes = <int>[];
  outer:
  for (var n = 2; n <= 30; n++) {
    for (var d = 2; d * d <= n; d++) {
      if (n % d == 0) continue outer;   // n is composite, try the next n
    }
    primes.add(n);
  }
  print(primes);
}

The test d * d <= n avoids computing a square root. Without the label, continue would only skip to the next divisor, and you would need a boolean flag instead.

Exercise 7: classify a score

Task. Write String grade(int score). Scores from 90 to 100 are 'A', 80 to 89 are 'B', 70 to 79 are 'C', and everything else from 0 to 69 is 'F'. Anything below 0 or above 100 is 'invalid'.

Hint. A switch expression with relational patterns reads like a table. Put the invalid case first.

Show the solution
DART
String grade(int score) => switch (score) {
      < 0 || > 100 => 'invalid',
      >= 90 => 'A',
      >= 80 => 'B',
      >= 70 => 'C',
      _ => 'F',
    };

Because cases are tried in order, >= 90 only sees values up to 100, and >= 80 only sees values below 90. That is why you do not write ranges like >= 80 && < 90. The same logic written with if/else if also works; the switch expression just makes the table shape obvious.

The second stand-in covers exercises 4 to 7. It also uses a tiny check function, which is the pattern behind every real test: compare the actual result with the expected one and report.

TypeScript Exercises 4 to 7 with checks (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Going further

When all seven feel easy, change them:

  • Extend exercise 1 to read the step from a variable and print the table backwards.
  • Make fizzBuzz accept a map of divisors to words, so you can add 7 => 'Bazz' without editing the switch.
  • Rewrite isLeapYear so it throws an ArgumentError for years below 1.
  • Make greet take a named parameter String? name with a default (see Parameters).

Small variations are how you find the edges of what you understand.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does 7 ~/ 2 evaluate to in Dart?

    The ~/ operator is truncating integer division, so 7 ~/ 2 is 3. The plain / operator would give the double 3.5.
  2. 2. In the FizzBuzz switch expression, why must (0, 0) come before (0, _)?

    (0, _) also matches (0, 0). If it came first, FizzBuzz would never be produced.
  3. 3. Why does greet avoid writing name!?

    The bang operator tells Dart to trust you that a value is not null. If you are wrong, the program crashes. A null check lets the compiler promote the type safely.
  4. 4. What does continue outer; do inside the inner loop of the primes example?

    A label lets continue and break target an enclosing loop. Here it moves straight on to the next candidate number.

Summary

  • Practice works best as a loop: predict, write, run, compare, then retype the solution from memory.
  • / returns a double, ~/ truncates to an int, and padLeft and toStringAsFixed format output.
  • Switch expressions on records and relational patterns turn decision tables into short, exhaustive code.
  • Null checks on local variables promote nullable types, so you rarely need the ! operator.
  • Labeled continue and break control nested loops without flag variables.

Continue with Practice: Classes and Collections.