Menu
Coddy logo textTech

The 'do-while' Loop

Part of the Fundamentals section of Coddy's Dart journey — lesson 44 of 94.

The do-while loop in Dart executes a block of code once before checking the condition, then continues to repeat as long as the condition is true.

Create a do-while loop that counts from 1 to 5:

void main() {
  int count = 1;
  
  do {
    print(count);
    count++;
  } while (count <= 5);
}

When you run this code, it will output:

1
2
3
4
5

Unlike a while loop, a do-while loop always executes at least once:

void main() {
  int number = 10;
  
  do {
    print("This will print once: $number");
    number++;
  } while (number < 5);
}

After executing the above code, the output will be:

This will print once: 10
challenge icon

Challenge

Beginner

In this challenge, you'll practice using the do-while loop in Dart. Unlike a regular while loop, a do-while loop always executes the code block at least once before checking the condition.

Your task is to create a program that:

  1. Reads a single integer from the input
  2. Uses a do-while loop to print all numbers from the input down to 1
  3. After each number, prints whether it's even or odd
  4. Continues until the number reaches 1
  5. Finally, prints the sum of all numbers that were displayed

For example, if the input is 4, your program should output:

4 is even
3 is odd
2 is even
1 is odd
Sum: 10

Notice that each line shows the number followed by whether it's even or odd, and the sum is printed at the end.

Cheat sheet

The do-while loop executes a block of code once before checking the condition, then continues to repeat as long as the condition is true.

Basic syntax:

do {
  // code block
} while (condition);

Example counting from 1 to 5:

int count = 1;

do {
  print(count);
  count++;
} while (count <= 5);

Unlike a while loop, a do-while loop always executes at least once, even if the condition is initially false:

int number = 10;

do {
  print("This will print once: $number");
  number++;
} while (number < 5);

Try it yourself

import 'dart:io';

void main() {
  // Read input
  String? input = stdin.readLineSync();
  int number = int.parse(input ?? '0');
  
  // Initialize sum
  int sum = 0;
  
  // Your code here - use a do-while loop to count down from number to 1
  // Print each number and whether it's even or odd
  // Calculate the sum of all numbers
  
  // Print the sum
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals