C - Do while loop
The do-while loop is a control flow statement that allows you to repeatedly execute a block of code at least once, and then continue execution as long as a specified condition is true. It is a post-test loop, meaning the condition is evaluated after each iteration.
do
{
// Code to be executed
} while (condition);
- The code block within the do-while loop is executed first.
- After executing the code block, the condition is evaluated.
- If the condition is true, the loop continues, and the code block is executed again.
- This process repeats until the condition becomes false. Once the condition is false, the loop is terminated, and the program proceeds to the next statement after the do-while loop.
int count = 1;
do
{
printf("%d\n", count);
count++;
} while (count <= 5);
In this example, the variable count is initially set to 1. The do-while loop executes the code block inside the do statement, which prints the current value of count, and then increments count by 1 using the count++ statement. After each iteration, the condition count <= 5 is evaluated. As long as the condition is true, the loop continues, and the code block is executed again. This process repeats until count reaches 6, at which point the condition becomes false, and the loop terminates.
The do-while loop guarantees that the code block will be executed at least once, regardless of the condition. This can be useful in situations where you need to perform an action before checking the condition.