C while loop

From all looping structures in C while is the simplest loop. It is called an entry-controlled loop because the conditions are tested before the start of the loop execution. The format of a while loop is given below:

Syntax

  1. while (test_condition) {
  2. body of the loop
  3. }

If the test_condition is true then the body of the loop will be executed. After execution the test_condition is again evaluated and if it is true the body will be executed once. As long as the condition is true the process continues. When the test_condition finally becomes false the control will be transferred out of the loop and continues with the statement immediately after the body of the loop.



Flowchart of while loop:


flowchart of while loop


Example of a while loop:

Example:

  1. #include <stdio.h>
  2. int main()
  3. {
  4. int i = 1;
  5. while(i <= 10) {
  6. printf("%d\n", i);
  7. i++;
  8. }
  9. return 0;
  10. }

Output:

1
2
3
4
5
6
7
8
9
10