C while loop

In this lesson, you will learn about the ‘while loop’ in C, its usage, and examples to better understand the topic.

The while loop in C

‘While loop’ is used constantly to perform a code block until the set situation is satisfied.
The while loops start with a condition. In each iteration, it checks the condition first. When the condition is true, the block of code is executed. The loop will run until the condition is evaluated to be false.

Basic Syntax of while loop

while (condition)
  {
    block of code to be processed here;
  }

“While (…) { … }” is the “situation” while loop block code is the situation to be assessed while loop
“code block …” is the code to be performed if the condition is satisfied

Flowchart of While Loop

flowchart

Example of while loop in C

Below is a code that prints the multiplication table of 2. The loop executes if the variable var is greater than or equal to 10. The loop is terminated after the condition becomes false

// Example of While loop
#include <stdio.h>
int main ()
{
  int var, evennumber;
  printf ("C ***While loop*** Example\n");
  printf (" -------While loop ---------\n");
  printf ("The table of %d \n", 2);
  while (var <= 10)
    {				//executes 10 times
      evennumber = 2 * var;
      printf ("2 * %d is %d \n", var, evennumber);
      var++;			// increment by 1
    }
  return 0;
}

Output

C ***While loop*** Example
-------While loop ---------
The table of 2
2 * 0 is 0
2 * 1 is 2
2 * 2 is 4
2 * 3 is 6
2 * 4 is 8
2 * 5 is 10
2 * 6 is 12
2 * 7 is 14
2 * 8 is 16
2 * 9 is 18
2 * 10 is 20
Note
Note: we increment the loop by one by using the ++ operator. If you forget to increment the variable, your program will enter an infinite loop and crash.

In the next lesson, will go through the do…while loop in C.