For Loop & Do-While Loop
For Loop & Do-While Loop
In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached.
1. Entry Controlled loops: In this type of loops the test condition is tested before entering the loop body. For
Loop and While Loop are entry controlled loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the end of loop body.
Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false.
do – while loop is exit controlled loop.
For Loop
}
For Loop Continued.
In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check
whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and
loop variable gets updated . Steps are repeated till exit condition meets.
1. Initialization Expression: In this expression we have to initialize the loop counter to some value. for
example: int i=1;
2. Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we
will execute the body of loop and go to update expression otherwise we will exit from the for loop. For
example: i <= 10;
3. Update Expression: After executing loop body this expression increments/decrements the loop variable by
some value. for example: i++;
For Loop Flow Chart
For Loop Example
cout<< “hello”<<endl;
cout<< “hello”<<endl;
For Loop Example Continued.
cout<< “hello”<<endl;
cout<< “hello”<<endl;
For Loop Example Continued.
cout<< “hello”<<endl;
cout<< “hello”<<endl;
Nested For Loop Example
int X = 2; int Y = 3;
cout<< j<< “ ”;
}
Do-While Loop
In do while loops also the loop execution is terminated on the basis of test condition. The main difference between
do while loop and while loop is in do while loop the condition is tested at the end of loop body. In do while loop the
loop body will execute at least once irrespective of test condition.
do{
// statements
update_expression;
} while (test_expression);
Do-While Loop Flow Chart
Do-While Example