Computer Programming II
CSC 202
Module 1 Lecture 5
LOOPS (cont.)
Dr. Akputu Oryina Kingsley
Content
2
▪ Choice of Loop
▪ Nested Loops
▪ Minimizing Numerical
Errors
Dr. Akputu Oryina Kingsley
3
Which Loop to Use?
The three forms of loop statements, while, do-while, and for, are
expressively equivalent; that is, you can write a loop in any of
these three forms. For example, a while loop in (a) in the
following figure can always be converted into the following for
loop in (b):
while (loop-continuation-condition) { Equivalent for ( ; loop-continuation-condition; ) {
// Loop body // Loop body
} }
(a) (b)
A for loop in (a) in the following figure can generally be converted into the following while
loop in (b) except in certain special cases (conditions to be explain in lab session):
for (initial-action; initial-action;
loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(a) (b)
Dr. Akputu Oryina Kingsley
4
Recommendations
Use the one that is most intuitive and comfortable for
you. In general, a for loop may be used if the number of
repetitions is known, as, for example, when you need to
print a message 100 times. A while loop may be used if
the number of repetitions is not known, as in the case of
reading the numbers until the input is 0. A do-while loop
can be used to replace a while loop if the loop body has
to be executed before testing the continuation condition.
Dr. Akputu Oryina Kingsley
5
Nested Loops
▪ Nested loops consist of an outer loop and one or more inner loops.
Problem: Write a program that uses nested for loops to print a
multiplication table
Dr. Akputu Oryina Kingsley
Minimizing Numerical Errors
6
▪ Numeric errors involving floating-point numbers are inevitable.
Here we look at how to minimize such errors through a problem.
▪ The Problem: is to sum a series that starts with 0.01 and ends
with 1.0. The numbers in the series will increment by 0.01, as
follows: 0.01 + 0.02 + 0.03 and so on.
Class: [Link]
Dr. Akputu Oryina Kingsley
7
End of Loop
Dr. Akputu Oryina Kingsley