Loop-Types in C++
Loops in C++
The sole purpose of loops is the repetitive execution of code.
Definition: Executing a set of statements required number of times until the condition becomes false is called a loop
Loops are also called as
iterative statements because the execution flow forms a cycle
C++ program to print odd numbers using while loop
//if n=10 it is true for i<1 to 1<=10
1 3 5 7 9
If you observe the execution flow in while, it is in a clockwise direction
The syntactical Structure of for loop is convenient than the remaining loops, It contains all the three parts in a single line
- Test condition
- Increment/ Decrement
for(initialisation; test_condition; increment/ decrement)
First test condition is checked and then if it is true loop body is executed, this process continues until the test condition becomes false
C++ to print multiplication table of a number using for loop
cout<<" which table you want to print:";
for(int i=1;i<=10;i++) //3 parts in single line
// n is constant , i=1 i=2 ...i=10
Which table you want to print:4
- Here n is constant if n=4, in first iteration i=1 we display 4*1. in the second iteration i value gets incremented to i=2 we display 4*2 .
- we continue this up to 4*10. After that, i becomes 11 and test condition fails because11<=10 is false, then control comes out of the loop.
- If you have the execution flow is in an anticlockwise direction.
Do while loop
- If we want to execute loop body at least once irrespective of the test condition then we need to go for a do-while loop
- Here loop body is executed first then the test condition is checked
According to syntax semicolon(;) is must at the end
C++ program to print numbers from 1 to 10 in reverse order
cout<<i<<"\t"; //loop body
while(i>=1); //test condition
10 9 8 7 6 5 4 3 2 1
Execution flow in a do-while is in the clockwise direction