Categories
b. Loops, Break and continue

while and

In programming, loops are used to repeat a block of code until a specified condition is met.

C programming has three types of loops.

  1. for loop
  2. while loop
  3. do…while loop

In the previous tutorial, we learned about for loop. In this tutorial, we will learn about while and do..while loop.

while loop

The syntax of the while loop is:

while (testExpression) {
  // the body of the loop 
}

How while loop works?

  • The while loop evaluates the testExpression inside the parentheses ().
  • If testExpression is true, statements inside the body of while loop are executed. Then, testExpression is evaluated again.
  • The process goes on until testExpression is evaluated to false.
  • If testExpression is false, the loop terminates (ends).

To learn more about test expressions (when testExpression is evaluated to true and false), check out relational and logical operators.

Flowchart of while loop

flowchart of while loop in C programming
Working of while loop

Example 1: while loop

// Print numbers from 1 to 5

#include <stdio.h>
int main() {
  int i = 1;
    
  while (i <= 5) {
    printf("%d\n", i);
    ++i;
  }

  return 0;
}

Output

1
2
3
4
5

Here, we have initialized i to 1.

  1. When i = 1, the test expression i <= 5 is true. Hence, the body of the while loop is executed. This prints 1 on the screen and the value of i is increased to 2.
  2. Now, i = 2, the test expression i <= 5 is again true. The body of the while loop is executed again. This prints 2 on the screen and the value of i is increased to 3.
  3. This process goes on until i becomes 6. Then, the test expression i <= 5 will be false and the loop terminates.

Leave a Reply

Your email address will not be published. Required fields are marked *