6. PARTS OF A LOOP
1. Initialization Expression - Before entering in a loop , its
control variables must be initialized. The initializations expression
gives the loop variables their first value.
2. Test Expression - The test expression is the expression whose
truth value decides whether the loop body will be executed or not.
3. Update Expression - The update expression change the values of
loop variables. The update expression is executed ; at the end of
the loop after loop body is executed.
4. The body of the Loop – The statements that are executed
repeatedly as long as the condition is true ,form the body of loop.
7. FOR LOOPFOR LOOP
For Loop executes a sequence of statements
multiple time
and abbreviates the code that manages the loop
variable.
Syntax: for (initialization; condition; update
expression)
Body of the loop;
Example: #include<iostream.h> output:
void main( ) 1
{ 2
for (int i=0; i<=5; i++) 3
8. Functioning oF For Loop in c++
For loop is used when we don’t know in advance how many times the loop will
times the loop will be executed .
The loop terminates as soon as the condition becomes false.
EXIT
9. WHILEWHILE LOOPLOOP
While loopWhile loop is an entry-controlled loop. It repeats a statement or
group of statements while a condition is true. It tests the
condition before executing the loop.
Syntax: initialization;
while (condition)
loop=body;
updating expression;
Example : #include<iostream.h> Output:
void main( ) 1
{ 2
int i=1 Initialization expression 3
while (i<=5) 4
cout<<“n”<<i; Body of loop 5
i++; Update expression
}
10. DO WHILE LOOPDO WHILE LOOP
Do while LoopDo while Loop is a exit-controlled loop. It evaluates its text expression at the
bottom of the loop after executing the loop body statements.
Syntax: initialization;
do
{
loop body;
updating expression;
}while (condition);
Example: #include<iostream.h. Output:
void main( ) 1
{int i=1 Initialization expression 2
do 3
{ 4
cout<<“n”<<i; Body of loop 5
i++; Update expression 6
}while (i<=5)
11. Comparison between
while loop and do while loop
While loop test condition before executing the loop body whereas do while loop
test condition after executing loop body.
While loop is a entry-controlled loop whereas do while loop is a exit-controlled
loop.
While loop is preferred when we don’t want to execute the loop body even once
in case the condition is false whereas do while loop is preferred when we want to