Objective #1: Be able to 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 an example of an
iteration 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: Be able to 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)
{
// one or more statements
}
- 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
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.
- Notice that semicolons are used to separate the three expressions
above, not commas.
- Example:
for (num = 1; num <= 3; num++ ) //
num is initialized to the value 1
{
// loop iterates while num is less than or equal
to 3
cout << num;
// num increments by 1 on each iteration
cout << endl;
}
// both statements execute
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 101 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 a loop only contains one body statement, the compiler doesn't require
the use of curly braces. But I recommend against doing so for CMPSC
101 students. According to our Coding
Standards for this course, you must use curly braces with for, while,
and do/while loops.
That is, do not use the following
syntax without curly braces:
for (num = 0; num < 10; num++)
cout << num << endl;
- According to our Coding Standards,
you must blank lines above and below any loop so that it stands out
and is easier to read by fellow programmers.
Objective #3: Be able to 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 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)
{
//
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 )
// control expression is true if num is greater than 100
{
cout << num;
num = num / 2;
// num is reassigned a new value during each iteration
}
Objective #4: Be able to 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 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.
- The do keyword is placed on
a line of code by itself at the top of the loop. A block of statements
follows it with a control expression after the keyword while
at the bottom of the loop.
do
{
//
body statements would be placed here
}while (control expression);
The control expression must evaluate to true in order for the do
while loop to iterate after the first time.
- Example:
do
{
cout << "Enter a number (0 to quit):
";
cin >> num;
sum = sum + num;
cout << "Current sum is " <<
sum << '\n';
} while (num != 0 );
- Don't forget to include the required semicolon after the control expression.
Objective #5: Be able to use the break and continue statements.
- 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.
- Notice in the following example how the break statement is used to break out of the loop when the user inputs 3 to exit:
int num = 0;
while (num != 3)
{
cout << "1 Books" << endl;
cout << "2 Movies" << endl;
cout << "3 Exit" << endl;
cin >> num;
if (num == 1)
{
cout << "Enter the quantity of books: ";
cin >> numBooks;
totalBooks += numBooks;
}
else if (num == 2)
{
cout << "Enter the quantity of movies: ";
cin >> numMovies;
totalMovies += numMovies;
}
else if (num == 3)
{
break;
}
totalCost += numBooks *BOOK_PRICE + numMovies * MOVIE_PRICE;
}
cout << totalCost << endl;
- 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, negative inputs are not added to the running total since the continue statement causes the statement runningTotal += num; to be bypassed:
while (num != 0)
{
cin >> num;
if (num < 0)
{
continue;
}
runningTotal += num;
}
The material below this point may not be included in this course or any exams. See the instructor for clarification.
Objective #6: Be able to use and interpret nested loops.
Notice the blank
lines around the inner loop for good style.