Fundamentals of Computer Programming - Old Questions

4. Differentiate between while and do while loop with example.

6 marks | Asked in 2073

Difference between while and do while loop

1. The while loop is pre-test loop, where firstly the condition is checked and if the condition is true then only the statements of the while loop execute. The do-while loop is a post-test loop. In the do-while loop, the statements of the do-while loop are executed after that, the condition is evaluated, and if the condition is true then again the statements of the do-while loop are executed.

2.

Syntax of while loop:

while (condition)

 {

   // statements

 }

Syntax of the do-while loop:

do

 {

   // statements 

 } while(condition);

3. The condition of the while loop is at the top of the loop but the condition of the do-while loop is at the bottom of the loop.

4. While loop can’t be terminated with a semicolon but the do-while loop should be terminated with a semicolon.

5. The statements of the do-while loop execute at least 1 time in every condition. In the while loop, the test expression evaluates false in first checking then the statements of the while loop is not executed. But the condition of the do-while loop is checked at the end of the loop, so it is guaranteed that the statements of the do-while loop execute at least once.

Example of while loop:

#include<stdio.h>

 int main()

 {

   int m,n;

   printf("Enter range: ");

   scanf("%d %d",&m, &n);

   while (m<=n)

   {

     if(m%2==0) 

        printf("%d ",m);

     ++m;

   }

   return 0;

 }

Example of do while loop:

 #include<stdio.h>

 int main()

 {

   int m,n;

   printf("Enter range: ");

   scanf("%d %d",&m, &n);

   do

   {

     if(m%2==0)

       printf("%d ",m);

     ++m;

   } while(m<=n);

   return 0;

 }