While Loop:

Loop executes the same block of code over and over again until the provided condition is true. We use while loop when we do not know the exactly that how many times loop will run.


How a While Loop works:

  • Initialize a variable on the basis of which condition is checked.
  • Check the condition. If the condition is true, the loop will run. Otherwise the loop will be terminated.
  • Change the vlaue of the variable such that the loop does not become infinite. When we change the value of the variable it will make the condition false and the loop will be terminated.

Syntax:

//initialize variable
while(check condition)
{
    //code
    //change value of variable
}

while.c
#include <stdio.h>

int main() {
  int i = 0;
    
  while (i < 5) {
    printf("My name is Sarah\n");
    i++;
  }
    
  return 0;
}

This will print name 5 times

Program to print couting from 1 to 5:

while.c
#include <stdio.h>

int main(){
  int i=0;
  while(i < 5){
    printf("%d\n", i);
    i++;
  }
  return 0;
}

Note: If we write true in condition, this while loop will become infinite. You can use ctrl + c on your keyboard to stop it.


Do While Loop:

While and do while loops are almost the same. The main diference is in the first iteration. In while loop, all iterations are done on the basis of condition. In do while loop, first iteration is done without checking the condition. After first iteration, it will work like while loop. The condition is checked and if it is true second iteration is done and this continues until the condition is true.

do-while.c
#include <stdio.h>

int main() {
  int i = 10;
    
  do {
    printf("%d\n", i);
    i++;
  }
  while (i < 5);
    
  return 0;
}

This code will execute one time, no matter the condition is false. But after first iteration, it will check the condition. If the condition is true, the loop will run. If the given condition is false, the loop will be terminated and the control will move out of the loop.