What is do while loop?
Do while loop have the following properties;
- Conditional loop structure
- Executes the statements until the given condition remains true. Stop the loop when given condition false.
- Similar to while loop.
- Body of loop must be executed at least once whether given condition is True or False.
- If the given condition is True then loop can execute multiple times.
What is the syntax of do while loop?
Syntax |
do { body of loop; statements; } While (condition); |
Example:
1 2 3 4 5 6 7 8 9 10 11
| #include<iostream> using namespace std; int main() { int number=1; do { cout<<“number is “<<number<<endl; number++; } while(number<=10); cout<<“you are outside the loop”; } |
Output: |
number is 1 number is 2 number is 3 number is 4 number is 5 number is 6 number is 7 number is 8 number is 9 number is 10 you are outside the loop |
Line 5:
- Integer type loop variable “number” is declared and initialized with value 1.
Line 6 to 10:
- Set of instructions for execution.
- Loop increment / Loop decrement
Line 11:
- There is a condition that loop will execute if value of number variable is less than or equal to 10.
Test Your Understandings |
1. If the given condition is false then no statement execute in do section? YES / NO |
do { cout<<“number is “<<number<<endl; } while(number<=10) 2. What is the error in code above? |