C++ 13: Do While Loop

 The do...while loop is a variant of the while loop with one important difference: the body of do...while loop is executed once before the condition is checked.

Its syntax is:

do {
   // body of loop;
}
while (condition);

Here,



  • The body of the loop is executed at first. Then the condition is evaluated.
  • If the condition evaluates to true, the body of the loop inside the do statement is executed again.
  • The condition is evaluated once again.
  • If the condition evaluates to true, the body of the loop inside the do statement is executed again.
  • This process continues until the condition evaluates to false. Then the loop stops.
Program:

#include <iostream>
using namespace std;

main()
{
    int e_s = 0o_s = 0;
    int i;

    do
    {
        /* code */
        cout << "Enter a number:";
        cin >> i;
        if (i % 2 == 0)
        {
            e_s = e_s + i;
        }
        else
        {
            o_s = o_s + i;
        }

    } while (i > 0);

    cout << " even numbers sum  is :" << e_s << endl;
    cout << "odd Numbers sum  is :" << o_s << endl;
}

Output:

Enter a number:34
Enter a number:3
Enter a number:3
Enter a number:4
Enter a number:-1
 even numbers sum  is :38
odd Numbers sum  is :5

Comments

Popular posts from this blog

C++ 38: Visibility Modes Public, Private and Protected