The do-while loop in C runs the code inside the loop once, and then checks the condition. If the condition is true, it repeats the loop; if the condition is false, the loop stops.
Syntax:
do {
// Code to be executed
} while (condition);
Explanation:
- do: Starts the loop and indicates that the code block inside the loop should execute.
- Block of code: The code inside the curly braces { } will execute at least once before checking the condition.
- while (condition): After executing the block of code, the condition is evaluated. If the condition is true, the loop will repeat; otherwise, it will terminate.
Example:
#include <stdio.h>
int main() {
int count = 1;
// do-while loop
do
{
printf("number:%d\n", count);
count++; // Increment the counter
}
while (count <= 5);
return 0;
}
Output:
number:1
number:2
number:3
number:4
number:5
number:2
number:3
number:4
number:5
Example: If we define count > 5 in the while loop then it will execute only one time.
#include <stdio.h>
int main() {
int count = 1;
// do-while loop
do
{
printf("number:%d\n", count);
count++; // Increment the counter
}
while (count > 5);
return 0;
}
Output:
1