In this tutorial we will learn about do-while loop in C programming language.
The do-while loop is very similar to the while loop but with one difference.
In the while loop we first check the condition and then execute the body of the loop if the condition is satisfied.
Whereas, in the do-while loop we first execute the body of the loop and then check the condition.
So, do-while loop guarantees that the body of the loop will be executed at least once.
Following is the syntax of a do-while loop.
do { //code... } while (condition);
We use the do and while keywords to create a do-while loop.
do
while
The body of the loop is executed as long as the condition is satisfied.
In the following example we will print 1 to 5 using do-while loop.
#include <stdio.h> int main(void) { //variable int count = 1; //loop do { printf("%d\n", count); //update count++; } while (count <= 5); printf("End of code\n"); return 0; }
Output
1 2 3 4 5 End of code
In the above code we have first set the count variable to 1. Then we enter the do-while loop.
count
Inside the loop we first print the value of count. Then we increment the value of count by 1 using the increment ++ operator.
++
Then we check the condition count <= 5 which means we will execute the code inside the body of the do-while loop as long as count is less than or equal to 5. When count becomes greater than 5 we exit the loop.
count <= 5
In the following example we will take an integer value from the user. If the value is less than or equal to 10 we will execute the body of the loop.
#include <stdio.h> int main(void) { //variable int count; //user input printf("Enter an integer: "); scanf("%d", &count); //loop while (count <= 10) { printf("%d\n", count); count++; } printf("End of code\n"); return 0; }
#include <stdio.h> int main(void) { //variable int count; //user input printf("Enter an integer: "); scanf("%d", &count); //loop do { printf("%d\n", count); count++; } while (count <= 10); printf("End of code\n"); return 0; }
Enter an integer: 10 10 End of code
In the above output we have entered 10 as user input and stored it in variable count. Since the condition count <= 10 is satisfied so, we executed the body of the loop.
count <= 10
In the above output we can see that we have entered 10 as user input. So, the given condition count <= 10 is satisfied so the code inside the body of the do-while loop is executed.
Enter an integer: 11 End of code
In the above output we can see that we have entered 11 as user input. So, the condition count <= 10 is not satisfied and hence the body of the while loop is not executed.
Enter an integer: 11 11 End of code
In the above output we have entered 11 as user input. But this time we get 11 as output. This is because in the do-while loop we first execute the body of the loop then we check the condition.