Wednesday, July 12, 2017

do-while loop in C++

C++ do-while Loop: Syntax and Examples


The do-while loop is a looping statement in C++ that executes the loop body at least once, even if the condition is false. This is because the condition is checked after executing the loop body.

Syntax

do {
// statements to be executed
} while (condition);

Key Points
  • The semicolon (;) after while(condition) is mandatory.
  • Loop body executes minimum one time
  • Condition is checked after execution
  • Useful when at least one execution is required (menus, input validation)

Example 1: Print Numbers from 1 to 5

#include <iostream>
using namespace std;

int main() {
    int i = 1;
    do {
        cout << i << " ";
        i++;
    } while (i <= 5);
    return 0;
}

Output:
1 2 3 4 5

Example 2: Sum of First 3 Numbers

#include <iostream>
using namespace std;

int main() {
    int i = 1, sum = 0;
    do {
        sum = sum + i;
        i++;
    } while (i <= 3);

    cout << "Sum = " << sum;
    return 0;
}

Output:
Sum = 6

Example 3: C++ program to print Z to A using do..while loop.

#include<iostream>
using namespace std;
int main()
{
  char ch='Z';
  do
  {
    cout << ch;
  ch = ch - 1;
  }
  while(ch >= 'A');
  return 0;
}

Output:

ZYXWVUTSRQPONMLKJIHGFEDCBA


* * * * *

No comments:

Post a Comment