Do While Loop
Part of the Fundamentals section of Coddy's Java journey — lesson 44 of 73.
The do-while loop is similar to the while loop, but with one key difference: the code block is executed at least once before the condition is checked. This means that the loop's body will always run the first time, regardless of whether the condition is true or false.
Here's the basic structure of a do-while loop:
do {
// Code to be executed
} while (condition);The do keyword marks the beginning of the loop, followed by the code block in curly braces. After the code block, the while keyword introduces the condition. The loop will continue to execute as long as the condition is true.
Here's an example:
int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 5);In this example, the code inside the do block will execute first, printing "Count: 0" and incrementing count to 1. Then, the condition count < 5 is checked. Since it's true, the loop continues.
This process repeats until count becomes 5, at which point the condition becomes false and the loop terminates.
The output of this code will be:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4Challenge
BeginnerWrite a Java program that uses a do-while loop to do the following:
- Initialize a variable
sumto 0. - Initialize a variable
numberto 1. - In each iteration, add
numbertosum. - Increment
numberby 2 in each iteration (i.e., 1, 3, 5, ...). - print
numberandsum:Sum is: [The sum value]Num is: [The number value] - Continue the loop as long as
numberis less than or equal to 50. - Print the final value of
sumafter the loop finishes:Final Sum: [The final sum value]
Cheat sheet
The do-while loop executes the code block at least once before checking the condition.
Basic structure:
do {
// Code to be executed
} while (condition);Example:
int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 5);The loop body executes first, then the condition is checked. The loop continues as long as the condition is true.
Try it yourself
public class Main {
public static void main(String[] args) {
// Initialize variables
int sum = 0;
int number = 1;
// Your code here
// Print the final sum
System.out.println("Final Sum: " + sum);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else