0% completed
The do...while loop is similar to the while loop, but it guarantees that the code block executes at least once before the condition is checked. This loop is useful when you want the code to run initially, regardless of the condition, and then continue running as long as the condition remains true.
do { // Code block to be executed } while (condition);
Below is an example that demonstrates a do...while loop which prints a message at least once even if the condition is false.
Explanation:
counter
and then increments it.counter < 10
is false after the first execution, the code block runs once because the condition is checked only after executing the block.Below is an example that uses a do...while loop to calculate the sum of numbers from 1 to 5.
Explanation:
number
equal to 1.number
to sum
and increments number
.number <= 5
is evaluated after each execution.number
exceeds 5, and then prints the final sum.The do...while loop is beneficial when you need to ensure that the code block executes at least once before evaluating the condition. Experiment with these examples to see how this loop can be used in scenarios where initial execution is necessary.
.....
.....
.....