Introduction
Fundamentals
C Flow Control
C Functions
C Arrays
While & Do-While Loops in C
Loops in c allow us to execute a block statement or group of statements multiple times until the given condition comes to false. In this tutorial, we will cover while loop and do-while loop in C Language with the help of examples.
1. While Loop in C Language:
While loop does not depend upon the number of iterations. In for loop the number of iterations was previously known to us but in the While loop, the execution is terminated on the basis of the test condition. If the test condition will become false then it will break from the while loop else body will be executed.
The syntax of the while loop is:
while (testExpression) {
// the body of while loop
}
How while loop works?
- The while loop evaluates the parenthesized() testExpression.
- The statements contained inside the while loop's body are executed out if testExpression is true. Then, testExpression is evaluated again.
- The process goes on until testExpression is evaluated to false.
- The loop terminates if testExpression returns a false result (ends).
Example 1: C Language While Loop
// while loop
#include <stdio.h>
int main()
{
// Initialization expression
int i = 5;
// Test expression
while(i < 10)
{
printf( "Hello Hashcodec\n");
// update expression
i++;
}
return 0;
}
Output :
Hello Hashcodec Hello Hashcodec Hello Hashcodec Hello Hashcodec Hello Hashcodec
Here, we have initialized i to 5.
- When i = 5, the test expression i < 10 is true. Hence, the body of the while loop is executed. This prints Hello Hashcodec on the screen and the value of i is increased to 6.
- Now, i = 6, the test expression i < 10 is again true. The body of the while loop is executed again. This prints Hello Hashcodec on the screen and the value of i is increased to 7.
- This process goes on until i becomes 10. Then, the test expression i < 10 will be false and the loop terminates.
2. Do-While Loop in C Language:
The do-while loop is similar to a while loop but the only difference lies in the do-while loop test condition which is tested at the end of the body. In the do-while loop, the loop body will execute at least once irrespective of the test condition.
The syntax of the do-while loop is:
do {
// the body of the loop
}
while (testExpression);
How do-while loop works?
- The do-while loop body is only executed once. The TestExpression is later evaluated.
- If TestExpression is true, the loop's body is executed once again, and TestExpression is evaluated once more.
- This step is repeated until TestExpression is false.
- If TestExpression is false, the loop ends.
Example 2: do-while loop
// do-while loop
#include <stdio.h>
int main()
{
int i = 2;
do
{
printf( "Hello Hashcodec\n");
// Update expression
i++;
// Test expression
} while (i < 1);
return 0;
}
Output :
Hello Hashcodec