C++ Do-While Loop

The do-while is another type of loop supported by C++ language. In the case of while loop and for loop – three expressions are compulsory. This is also true for do-while, but in a different way.

Advertisements

do-while Loop Structure

The do part allow the code block to execute first and then the while part perform a test for terminating the loop. The loop terminates when the test condition is false.

Advertisements

The general structure for do-while is given below.

expression1;
do
{
         do something;
         expression2:
}while(expression3);

Graphical Representation of do-while

The graphical representation of do-while is useful in making flowcharts for C++ programs.

do-while Loop Diagram

Example Program: do-while


//do-while loop
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
    //Variable decalaration
    
    int sum;
    int value;
    
    
    //Initialization
    
    sum = 0;
    value = 10;
    
    
    //Do-while to compute the results
    
    do
    {
               sum = sum + value;
               value--;
               
    }while(value >= 0);
    
    //printing outputs
    
    cout << "Sum = " << " " << sum << endl;
        
    system("PAUSE");
    return EXIT_SUCCESS;
}

Output:

Sum = 55


Advertisements

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Exit mobile version