C Programming
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.
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.
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.
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.
while loop | do-while loop |
---|---|
Code
| Code
|
Run #1 Output
In the above output we have entered 10 as user input and stored it in variable count. Since the condition | Run #1 Output
In the above output we can see that we have entered 10 as user input. So, the given condition |
Run #2 Output
In the above output we can see that we have entered 11 as user input. So, the condition | Run #2 Output
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. |
ADVERTISEMENT