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
5Unlike 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: 10Challenge
BeginnerIn 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:
- Reads a single integer from the input
- Uses a
do-whileloop to print all numbers from the input down to 1 - After each number, prints whether it's even or odd
- Continues until the number reaches 1
- 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: 10Notice 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
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Comparison OperatorsLogical ANDLogical ORLogical NOTType Test OperatorsRecap - Making Comparisons7Working with Strings
String ConcatenationString InterpolationMulti-line StringsString PropertiesBasic String Methods10Collections - Maps Basics
What are Maps?Creating a MapAccessing Values by KeyKey-Value PairsGetting Map SizeGetting KeysGetting ValuesChecking if a Key Exists13Null Safety In Depth
Understanding NullNullable TypesNon-Nullable TypesNull Assertion OperatorLate InitializationRecap - Handling Null Safely16Fundamentals Challenges
Challenge: List of calculationChallenge: Sum of numbersChallenge: Find product2Variables and Basic Data Types
What are Variables?StringsIntegers (int)Doubles (double)Booleans (bool)Type Inference with 'var'Final VariablesConstant VariablesNaming ConventionsBasic Null SafetyRecap - Declaring Variables8Control Flow - Loops
The 'for' LoopThe 'while' LoopThe 'do-while' LoopUsing 'break' in LoopsUsing 'continue' in LoopsRecap - Repeating Code3Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorIncrement and DecrementAssignment ShortcutsRecap - Simple Calculations6Control Flow - Decision Making
The 'if' StatementThe 'else' StatementThe 'else if' StatementRecap - Simple DecisionsNested 'if' StatementsThe 'switch' Statement9Collections - Lists Basics
What are Lists?Creating a ListAccessing by IndexGetting List LengthAdding ElementsRemoving ElementsChecking if a List is EmptyIterating Over a List12Functions Advanced
Optional Positional ParametersNamed ParametersRequired Named ParametersDefault Parameter ValuesRecap - Function Parameters15Project: Simple Calculator
Setting UpDeclaring Number