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

While loop

while(test_condition) 
{
loopbody;
update_stmts;
}

C++ program to print odd numbers using while loop

main()
{
int n,i=1;
cout<"enter range:";
cin>>n;
while(i<=n)//test-condition
//if n=10 it is true for i<1 to 1<=10
{
cout<<i<<"\t";//loop body
i=i+2;//update stmt
}
}
Loop Types in C++

O/P

enter range:10
1 3 5 7 9

If you observe the execution flow in while, it is in a clockwise direction

For loop

The syntactical Structure of for loop is convenient than the remaining loops, It contains all the three parts in a single line 

  • Initialization
  • Test condition
  • Increment/ Decrement

Syntax

for(initialisation; test_condition; increment/ decrement) 
{
Loop body;
}

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

main() 
{
int n;
cout<<" which table you want to print:";
cin>>n;
for(int i=1;i<=10;i++) //3 parts in single line
{
cout<<n<<"*"<<i<<"="<<n*i<<"\n";
// n is constant , i=1 i=2 ...i=10
}
}

O/P

Which table you want to print:4 
4*1=2
4*2=8
4*3=12
4*4=16
4*5=20
4*6=24
4*7=28
4*9=36
4*10=40
  • 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

Syntax

do 
{
body;
increment/decrement stmts;
}
while(test_condition);

According to syntax semicolon(;) is must at the end

C++ program to print numbers from 1 to 10 in reverse order

main() 
{

int i=10;

do
{
cout<<i<<"\t"; //loop body
i--;//inc/dec stmts;
}

while(i>=1); //test condition

}

O/P

10 9 8 7 6 5 4 3 2 1

Execution flow in a do-while is in the clockwise direction