do...while loop in c++ with program example

do...while loop in c++ with program example

The "do-while" loop

The "do-while" loop is also a conditional loop statement. It is like a while loop but in this on is loop the condition is tested after executing the statements of the loop.


The syntax of the "do-while" is:

                               do 
                                        {
                                               statements;
                                        }
                                         while (condition);
where

do                  is a keyword of C++. It indicates the starting of the do-while loop.

statements statement enclosed in braces represents the body of loop.

condition   It is the condition that must remain true for the execution of the loop.


In "do-while" loop the body of the loop is executed at least once before the condition is tested. It is repeatedly executed as long as the test condition remains true. If the given condition becomes false at any stage during the program execution , the loop terminates and the control shifts to the statement that comes immediately after the keyword "while".

           The difference between the "while" and "do-while" loop is that:

  • In while loop test condition comes before the body of the loop. First the condition is tested and then the body of the loop is executed.
  • In "do-while" loop, the body of the loop comes before the test condition . The body  of the loop is executed and then the condition is tested.

Program example:

Print first ten natural number on the computer screen by using : do-while" loop.



# include<iosteam.h>
main()
         {
                 int=n;
                    n=1;
                     do
                   {
                             cout<<n<<endl;
                             n++;
                    }
                            while (n<=10);
          }


The flowchart of "do-while" loop is given below:


Creative Commons License
Pakistan How by Tahira Aijaz is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.