0 votes
in C Plus Plus by

What is the difference between while and do while loop? Explain with examples.

1 Answer

0 votes
by

The format of while loop in C++ is:

While (expression)

{statements;}

The statement block under while is executed as long as the condition in the given expression is true.

Example:

#include <iostream.h>

 int main()

{

               int n;

               cout<<”Enter the number : “;

               cin>>n;

              while(n>0)

              {

                              cout<<” “<<n;

                              --n;

              }

              cout<<”While loop complete”;

 }

In the above code, the loop will directly exit if n is 0. Thus in the while loop, the terminating condition is at the beginning of the loop and if it's fulfilled, no iterations of the loop are executed.

Next, we consider the do-while loop.

The general format of do-while is:

do {statement;} while(condition);

Example:

#include<iostream.h>

int main()

{

               int n;

               cout<<”Enter the number : “;

               cin>>n;

               do {

                          cout<<n<<”,”;

                          --n;

                     }while(n>0);

                    cout<<”do-while complete”;

}

In the above code, we can see that the statement inside the loop is executed at least once as the loop condition is at the end. These are the main differences between the while and do-while.

In case of the while loop, we can directly exit the loop at the beginning, if the condition is not met whereas in the do-while loop we execute the loop statements at least once.

Related questions

0 votes
0 votes
asked Mar 17, 2020 in C Plus Plus by SakshiSharma
0 votes
0 votes
asked Oct 11, 2021 in Python by rajeshsharma
...