Understanding the Do-While Loop in C: Guaranteed Execution

Explore the do-while loop in C, a control structure that guarantees at least one execution of a code block before checking a specified condition at the end of the loop. Learn how this feature can be useful for scenarios where you need to ensure that the loop runs at least once.



Do-While Loop in C

The do-while loop executes a block of code at least once before checking a condition at the end of the loop.

Syntax


do {
statement(s);
} while(condition);
    

The loop starts with the do keyword and ends with the while keyword. The condition is checked after the loop body is executed.

Example


#include <stdio.h>

int main(){
int a = 1;

do{
    printf("Hello World\n");
    a++;
} while(a <= 5);
printf("End of loop"); 

return 0;
}
    
Output

Hello World
Hello World
Hello World
Hello World
Hello World
End of loop
    

The variable a starts at 1. The loop prints "Hello World" and increments a until a is greater than 5.

Difference Between while and do-while Loops

The main difference is the location of the test condition. In a while loop, the condition is at the beginning, while in a do-while loop, the condition is at the end.


#include <stdio.h>

int main(){
int a = 3, b = 3;

printf("Output of while loop: \n");
while(a < 5){
    a++;
    printf("a: %d\n", a);
}

printf("Output of do-while loop: \n");
do{
    b++;
    printf("b: %d\n", b);
} while(b < 5);

return 0;
}
    
Output

Output of while loop:
a: 4
a: 5

Output of do-while loop:
b: 4
b: 5
    

Changing the initial value of both variables to 10 will show the difference:

Output

Output of while loop:

Output of do-while loop:
b: 11
    

The while loop does not execute if the condition is false initially, but the do-while loop executes at least once.