C++ Do-While Loop

Advertisements
Advertisements

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.

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.

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
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

Bestseller

Let Us C++

One of the best selling book in C++ programming language. A perfect book for beginners and people who want to prefer self-study in step by step manner. Simple and easy narration style made this book very popular. The book assumes that you don’t have programming experience and starts with basic to more advanced topics.


Advertisements
Advertisements
Advertisements