Difference between while loop and do while loop

while loop

While Loop is an entry-controlled loop that evaluates the condition before executing the body of the Loop, the body of the Loop will be executed only if the condition is True.

Syntax:

while (condition) {
  // code block to be executed
}

 

Example:

#include<stdio.h>

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

Output:

1
2
3
4
5

 

do while loop

A do-while Loop is an exit-controlled loop that evaluates the condition after the execution of the body.

  • The body of the Loop is always executed (at least once)
  • Once the body is executed, then it checks the condition.

 

Syntax:

do {
  // code block to be executed
}
while (condition);

 

Example:

#include<stdio.h>

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

 

Output:

1
2
3
4
5

Difference between while and do while loop

while loopdo while loop
1. while loop is entry control loop1. do-while loop is exit control loop
2. while loop tests the condition before executing the loop body2. do-while tests the condition at the end of the loop body
3. It is a pre-test loop3. It is a post-test loop
4. There is no semicolon at the end of the loop4. The semicolon is must required at the end of the loop.

Leave a Reply

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