Do.. While loop
The do ... while
loop is similar to the while
loop, but with a key difference: it guarantees that the loop body will execute at least once. Its syntax is as follows:
Understanding the Do While Loop
In a do ... while
loop, the condition is evaluated after the loop body has executed. This means that even if the condition is initially false
, the code inside the loop will run once before the condition is checked. This characteristic makes the do ... while
loop a bottom-tested loop.
Example: Calculating the Average of a Series of Numbers
Let’s rewrite the previous example of calculating the average using a do ... while
loop:
Code Explanation
- Loop Execution: The
do ... while
loop starts by executing the code block. The user is prompted to enter a number, which is read and converted to a double for more accurate input. - Exit Condition: If the user enters
0
, thefinished
variable is set to true, which will terminate the loop on the next evaluation. If the input is not zero, the program increments thecount
and adds the input value tosum
. - Average Calculation: After exiting the loop, the program checks if
count
is greater than0
to avoid division by zero. If valid numbers were entered, the average is calculated and displayed. If no numbers were entered, an appropriate message is shown.
Warning
Be sure to include a semicolon at the end of the do ... while
loop. This is a common syntax requirement in C# and can lead to errors if omitted.