C++ 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 test expression is checked.
The syntax of do..while loop is:
do {
   // codes;
}
while (testExpression);

How do...while loop works?

  • The codes inside the body of loop is executed at least once. Then, only the test expression is checked.
  • If the test expression is true, the body of loop is executed. This process continues until the test expression becomes false.
  • When the test expression is false, do...while loop is terminated.

Flowchart of do...while Loop

Flowchart of do while loop in C++ programming

Example 2: C++ do...while Loop

  1. // C++ program to add numbers until user enters 0
  2. #include <iostream>
  3. using namespace std;
  4. int main()
  5. {
  6. float number, sum = 0.0;
  7. do {
  8. cout<<"Enter a number: ";
  9. cin>>number;
  10. sum += number;
  11. }
  12. while(number != 0.0);
  13. cout<<"Total sum = "<<sum;
  14. return 0;
  15. }
Output
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: -4
Enter a number: 2
Enter a number: 4.4
Enter a number: 2
Enter a number: 0

Comments

Popular posts from this blog

C++ Virtual Function

Function Overriding in C++ [With Example]

C++ Inheritance(Why inheritance should be used?)