CMPSC 201
Ch. 5 Notes
Objective #1: Explain the importance of loops in programs.
- In order to write a nontrivial computer program, you almost always need
to repeat sets of statements over and over again. Repetition (or iteration)
structures are used to make this occur. Loops are an example
of a repetition structures in most programming languages. There are three
kinds of loops in C++: for loops, while loops and do/while
loops.
- It is important to be aware of how many iterations
a given loop is expected to perform. Each pass of the loop is an iteration.
If a loop does not iterate a finite number of times, it is considered to be
an infinite loop. Rarely would a programmer ever intentionally incorporate
an infinite loop into a program, however it is easy to do so by mistake.
Objective #2: Use for loops.
- A for
loop usually executes a specific number of iterations. Use a for
loop when you know exactly how many times a set of statements must be repeated.
In this situation, a for loop is called a fixed-count loop. However,
there are times when a user could be allowed to input data and to use that
data to control a for loop. In those situations, the for loop is a variable
condition loop. As we will see, it is usually a better choice to use a
while or do while loop in variable condition situations and to use a for loop
in fixed-count situations.
- A for loop is often called a determinate or definite loop because
the programmer knows exactly how many times it will iterate in most fixed-count
situations. You can mathematically determine the number of iterations by deskchecking
the logic of the loop.
- The for loop is also an example of a pretest (or entrance-controlled)
loop since its control expression is tested at before its first iteration.
Therefore, if the control expression evaluates to FALSE, the for loop will
never iterate even once.
- After the keyword for a set of parentheses is necessary with three
expressions as parameters.
for (initializing expression; control expression; step expression)
{
// one or more statements
}
- The initializing expression
(sometimes called the initializing
list) sets the counter variable for
the loop to its initial value.
- The control expression
ends the loop at the specified moment.
- The step expression (sometimes
called altering list) changes the
counter variable,effectively determining the number of iterations. The
counter variable often increments by one, but it may increment, decrement,
or count in other ways.
- Example:
for (num = 1; num <= 3; num++ )
// the counter variable num is initialized to the
value 1
{ //
the loop will iterate while num is less than or equal to 3
cout << num; //
the counter variable num increments by 1 on each iteration
cout << endl;
}
//
both statements are executed in the body of the loop on
each iteration
- It is possible to have variable increase by a value other than one. For
example the following loop would iterate 4 times with the variable num taking
on the values 1, 4, 7, and 10. The step expression adds 3 to the value of
num on each iteration.
for (num = 1; num <= 10; num
= num + 3)
It is a common error though for students to use
for (num = 1; num <= 9 ; num + 3)
which causes a compile error.
- It is possible to initialize the loop variable within the initializing expression.
But I recommend against CMPSC 201 students initializing loop variables within
the loop and may deduct points for doing so. Students are required to declare
loop variables at the top of the function (e.g. main function) where they
are used.
for (int num = 1; num <= 9; num = num
+ 3)
{
cout <<
num << endl;
}
- If an if statement only contains one body statement, the compiler doesn't
require the use of curly braces. But I recommend against doing so for CMPSC
201 students. That is, for this course, I require students to use curly braces
to always be used with for, while, and do/while loops as well as if statements.
Do not use the following syntax without
curly braces:
for (num = 0; num < 10; num++)
cout << num << endl;
- I also require that you place blank lines above and below any for, while,
and do/while loops so that your loops stand out and are easier to read by
fellow programmers.
Objective #3: Use while loops.
- A while
loop does not necessarily iterate a specified number of times.
Rather, as long as its control expression
is TRUE, a while loop will continue to iterate. This type of loop is very
useful in when used as a variable condition loop, particularly when the user
is given the opportunity to interact with the program.
- A while loop is considered to be an indeterminate or indefinite
loop because usually only at run-time can it be determined how many times
it will iterate.
- Since its control expression is evaluated before its first iteration, it
is considered to be a pretest loop.
- After the keyword, while, a control expression is necessary.
while (control expression)
{
//
one or more statements
}
The control expression must evaluate to TRUE in order for the while loop
to iterate even once.
- Example:
while (num > 100 )
// the control expression is TRUE if the num is greater than 100
{
cout << num;
num = num / 2;
// the variable num is reassigned a new value during each iteration
}
Objective #4: Use do while loops.
- As with a while loop, a do
while loop does not necessarily iterate a specified
number of times. However, it is guaranteed that a do while loop will iterate
at least one time because its control expression is placed at the end of the
loop. This loop is useful when you want to guarantee at least one iteration
of the loop. Because the control expression is at the end of the loop, the
do while is called as a posttest, exit-controlled, or bottom
checking loop.
- Like a while loop, a do while loop is a better choice for variable condition
situations rather than fixed-count ones. Therefore, it is often considered
to be an indeterminate or indefinite loop.
- Often, sentinels are used with while or do while loops. A sentinel
is a reserved value that is the user enters to indicate that the loop should
stop iterating. For example, you may ask the user to enter his exam scores
(numbers between 0 and 100) and to enter the special value of -99 to indicate
that he/she is finished entering scores. Of course, the -99 is not counted
nor meant to be an actual exam score. The code might look like this where
the sentinel is -99:
do
{
cout << "Enter an exam score (-99 to quit):
";
cin >> score;
if (score != -99)
{
numExams++;
total = total
+ score;
cout <<
"Current exam average is " << total / numExams << endl;
}
}while (num != -99 );
Objective #5: Use the break and continue statements.
- A break
statement is used to stop the execution of a loop or switch structure immediately
and to continue by executing the statement that comes directly after the loop
or switch structure. Only use the break statement when it is not practical
to control the execution of a loop with its control expression. That is, only
use a break statement when absolutely necessary.
- A continue
statement is used to stop the execution of the statements in the loop's body
on that particular iteration and to continue by starting the next iteration
of the loop.
Objective #6: Use nested loops.