While loop in C with Examples

While loop in C with Examples

The While loop in C Programing language is a control loop statement in C programming language. It works on validating the test condition which is given to it. While loop evaluated the given conditions, if the condition is true, then the body of the while loop will be executed.

And If the condition is false, then the body of the while loop will be skipped.

These condition checks are performed by again and again till the conditions validate and each time body of while loop gets executed.

Execution of the body will continue until the test condition gets failed and return false. After the failing of test condition control will be transferred out of the loop.

On exit from the while loop program, will continues the execution of the next statement immediately after the while loop.

Syntax of while loop

while (test condition) {
  body of the loop
}

Program 1 : Print 1 to 5 using while loop in C

The below program is to print the value from 1 to 5 using a while loop.

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

Output

1
2
3
4
5

Explanation of the above program in detail

In the above example of the while loop program using C language, First I have taken an integer value i and assigned a value 1. So that when the while loop will start execution then they have value in i.

Now while loop will begin. The first time while loop will compare the value of i with then and in comparison, it will validate that is the value of i is smaller or equal to 5 is true or false.

If the condition is satisfied then the body will execute and print the value of i and increase the value of i by 1.

Now next time again while the loop will execute and check the condition, if the condition will satisfy the value will be printed otherwise the loop will be terminated. Like when the value of I becomes 11 then condition validation failed and the loop is terminated.

Program 2: C Program to Print even numbers using While loop

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

Output

2
4
6
8
10

I hope now you have understood the concept of while loop.