Wyo C++ - Ch. 8 Notes
Objective #1: Explain the importance of loops in programs.
- In order to write a non-trivial computer program, you almost always need
to use one or more loops. Loops allow your program to repeat groups
of statements a specified number of times. Loops are classified as a type
of iteration (or repetition) structure.
- It is important to be aware of how many iterations
a given loop is expected to perform. 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 always executes a specific number of iterations. Use a for loop when
you know exactly how many times a set of statements must be repeated.
- A for loop is called a determinate or definite loop because
the programmer knows exactly how many times it will iterate. You can mathematically
determine the number of iterations by deskchecking the logic of the loop.
- After the keyword, for, a set of parentheses is necessary with three
expressions as parameters.
for (initializing expression; control expression; step expression)
{
statement or statement block
}
- The initializing
expression sets the counter variable for the loop
to its initial value.
- The control expression
ends the loop at the specified moment.
- The step expression
(or incrementing expression) 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 (i = 1; i <= 3; i++ )
// the counter variable, i, is initialized to the
value 1
{
cout <<
i ; //
the loop will iterate while i is less than or equal to 3
cout <<
'\n'; //
the counter variable, i, increments by 1 on each iteration
}
//
two statements are executed in the body of the loop on
each iteration
- It is possible to initialize the loop variable within the initializing expression.
But I recommend against Wyo C++ 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;
}
- You can increment the loop variable by more than 1 if you wish. In the following
loop, the loop variable is incremented by 3 on each iteration:
for (i = 1; i<= 9; i = i + 3)
{
cout <<
num << endl;
}
Of course, the compound operator could be used with i += 3 replacing the i
= i + 3 incrementing expression.
It is a common error for students to try to use:
for (i = 1; i <= 9 ; i + 3)
instead of the required
for (i = 1; i <= 9; i = i + 3)
- Some programmers use a for loop like,
for (;;)
{
cout << "Enter a number: ";
cin >> userInput;
if (userInput != -99)
{
runningTotal += userInput;
}
else
{
break;
}
}
in which case the infinite for loop will run until the break condition
is met. Note that technically the initializing, control, and incrementing
expressions of a for loop are optional. However, this is poor coding since
it can lead to logical errors and you should avoid using break statements
and infinite loops when possible.
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
situations where a for loop would be ineffective, 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.
- A while loop is also considered to be a top-checking (or pretest)
loop, since the control expression is located on the first line of code with
the while keyword. That is, if the control expression initially evaluates
to FALSE, the loop will not iterate even once.
- After the keyword, while, a control expression is necessary.
while (control expression)
{
statement or statement block
}
- The control expression must evaluate to TRUE in order for the while loop
to iterate.
- Example:
while (num > 100 )
// the control expression is TRUE if the variable 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.
- Like a while loop, a do while loop is considered to be an indeterminate
or indefinite loop.
- A do while loop is considered to be a bottom-checking (or posttest)
loop, since the control expression is located after the body of the loop after
the while keyword. A do while loop is guaranteed to iterate at least once
even if the control expression evaluates to FALSE.
Objective #5: Use the break and continue statements with loops appropriately.
- A break
statement is used to stop the execution of a loop immediately and to continue
by executing the statement that comes directly after the loop. 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.
while (num != -99)
{
cin >> num;
if (num == -99)
{
break;
}
sum += num;
}
however it would be better to write this loop to avoid the use of a break
statement if possible since break statements found within a loop can be difficult
to pick out by those who read over your code. This version of the same loop
would be better for clarity.
num = 0;
while (num != -99)
{
sum += num;
cin >> num;
}
- 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.
In the following example, all inputed positive numbers less than or equal
to 100 are subtotaled. If a negative value is inputed, it is not added to
the subtotal but rather the loop continues with the next iteration. Any value
greater than 100 could be entered to terminate the loop.
while (num <= 100)
{
cin >> num;
if (num < 0)
{
continue;
}
sum += num;
}
Objective #6: Use nested loops effectively when appropriate.
Objective #7: Use flag variables and sentinel values to control indeterminate
loops.
- A sentinel value is a special value that is used to cause an indeterminant
loop to terminate. Often sentinel values are inputed by a user to indicate
the end of input. For example, the sentinel value of -99 is used in the loop
below to terminate the loop which calculates a bowling average. It should
be noted that the -99 is being used as a sentinel value since it is impossible
in the sport of bowling to bowl a score of -99. Therefore the sentinel value
will not mistakenly be entered as an inputed bowling score.
cout << "Enter a bowling score (-99 to quit): ";
cin >> score;
while (score != -99)
{
sum += score;
numGames++;
cout << "Enter a bowling score (-99 to quit):
";
cin >> score;
}
cout << "Your average is " << double (sum) / numGames
<< endl;
- A flag variable is a special variable that is used to control an indeterminant
loop. A flag variable is usually an int that is assigned the values 0 or 1
to indicate false or true respectively. Often though a variable of the bool
data type is used for flag variables.
bool choseBook= false;
bool choseCD = false;
do
{
cout << "1 Book" << endl;
cout << "2 CD" << endl;
cout << "3 Exit" << endl;
cout << "Enter a menu option: ";
cin >> choice;
if (choice == 1)
{
cout << "You chose book." <<
endl;
choseBook = true;
}
else if (choice == 2)
{
cout << "You chose cd."
<< endl;
choseCD = true;
}
}
while (choice != 3 && choseBook != true && choseCD != true);