Académique Documents
Professionnel Documents
Culture Documents
(continued)
Counter-Controlled Loops
Loops can be controlled using a
counter rather than a sentinel value
These are called countercontrolled loops
Sample Output of
Miguel Music Companys Program
Format:
for( initialization; expression ; update )
{
1 or more statements;
}
No ;
goes here
update
code
false
test
true
statement(s)
Solution to for
Square Loop
\t is used for tab (must be place in cout
statement)
cout<< \t
Solution to for
Square Loop
cout<< "An example of a Number
and its Equivalent Square" <<endl
<<endl ;
cout<< "Number \t \tSquare"
<<endl ;
{for (int y=1; y<=10; y++)
cout<< y <<"\t \t" <<y*y <<endl;
}
Review of
Pretest vs. Posttest Loops
Whether you use a while loop or for
loop, the loop body might never
execute.
Both of these loops are pretest loops
loops in which the loop control variable
is tested before the loop body is
executed.
Notice the
required ;
statement(s)
true
condition
false
Answer
3. The do-while loop controls a loop that
tests the loop-continuing condition at the
bottom of the loop.
Nested Loop
A nested loop is a loop inside the body
of another loop
You can place any statements you need
within a loop body.
You can nest any type of loop (while,
for, do-while).
Nested Loop
A loop that completely contains another
is an outer loop (row).
A loop that falls entirely within the body
of another is an inner loop (column).
You can place one loop (the inner, or
nested loop) inside another loop (the
outer loop)
Multiplication Table
Sample Output
Solution to
Multiplication Table
cout<< "[5x5] Multiplication Table" <<endl;
for (int outer=1; outer<=5; outer++)
{
cout<< endl <<outer;
for(int inner=2; inner<=5; inner++)
{
cout<< "\t" <<outer * inner <<" ";
}
}
outer loop
inner loop
Nested for
Sample Output
Solution to
Nested for
outer loop
Thank You
Prepared by: Prof. LRQ Natividad