The iteration statements allow a set of instructions to be performed
repeatedly until a certain condition is fulfilled. The iteration statements are
also called loops or looping statements in C++.
C++ provides three types of loops
- For Loop
- While Loop
- Do-while Loop
The for Loop
The for loop is the sassiest to understand of C++ loops. All its
loops-controls elements are gathered in one place (on top of the loop),while in
the other loop construction in C++, they are scattered about the program. The
general form (syntax) of the for loop statement is
for( initialization expression(s) ; test-expression ; update
expression(s) )
body of the loop ;
Below is an example.
The while Loop
The second loop available in C++ is the while loop. The while
loop is an entry-controlled loop. The syntax of a while loop is
While(expression)
Loop body
Where the loop body may contain a single statement, a
compound statements or an empty statement. The loop iterates while the
expression evaluates to true. When the expression becomes false, the program
control passes to the line after he loop-body code.
In a while loop, a loop control variable should be initialized
before the loop begins as an uninitialized variable can be used in an
expression. The loop variable should be updated inside the body of the while.
Below is an example.
The do-while Loop
Unlike the for and while loops, the do while is an exit
controlled loop i.e. it evaluates its test expression at the bottom of the loop
after executing its loop-body statements. This means that a do-while loop
always executes at least once, even when the test expression evaluates to false
initially.
The syntax of the do while loop is
Do
{ statement ; }
While (test-expression) ;
The braces {} are not necessary when the loop body contains a
single statement.
The following example prints all upper cases
Char ch=”A” ;
Do
{ cout<<”/n”<<ch
Ch++; }
While (ch<=Z) ;
The above loop prints characters from ‘A’ onward until the condition ch<=Z becomes false.
0 comments:
Post a Comment