CSCI 201 Study Aid: Loops
- Every programming language contains three general types of
structures: sequence, selection, and looping.
- A sequence
structure is a set of program statements that are executed
sequentially;
- A selection
structure executes one of two or more possible avenues of code;
- A loop executes, or could execute,
the same block of code multiple numbers of times.
- Consider the
following problem, one from elementary mathematics: adding a sequence
of numbers.
Problem Statement - Add the first 100 positive integers. That
is, 1 + 2 + ... + 98 + 99 + 100.
If a loop structure did not exist, here is how we would have to write
a C++ program to solve this problem.
- // Program fragment to all the first 100 positive integers.
int sumSoFar = 0; // Initialize the sum to zero. Without initialization,
// there could be trash in the memory cell.
sumSoFar = sumSoFar + 1;
sumSoFar = sumSoFar + 2;
sumSoFar = sumSoFar + 3;
sumSoFar = sumSoFar + 4;
sumSoFar = sumSoFar + 5;
// Another 92 statements like that
sumSoFar = sumSoFar + 98;
sumSoFar = sumSoFar + 99;
sumSoFar = sumSoFar + 100;
cout << "The sum is: " << sumSoFar << endl;
Notice that the adding part
of the program is 100 lines long.
Here is the same process, using a loop structure.
- // Program fragment to all the first 100 positive integers.
int sumSoFar = 0; // Initialize the sum to zero. Without
// initialization, there could be trash
// in the memory location.
for (int i = 1; i <= 100; i = i + 1)
sumSoFar = sumSoFar + i;
cout << "The sum is: " << sumSoFar << endl;
Notice that the adding part of the program is only 2 lines long. If
we wanted the sum of the first 500, or 5000 or 50,000 numbers the
adding part would still only be 2 lines long! This particular kind of
looping structure is called a for loop.
Common uses of loops
- There are two main kinds of loops:
- Counter based - where we perform the action a fixed number
of times
- Variable-condition - where we perform the action until a
certain condition is satisfied
- There are a huge range of possible applications for loops,
here a few examples:
- Keep performing some action until a user enters
a command to quit
- Step through all the elements of a list,
performing some actions on each element
- Getting correct input: keep prompting the
user for a specific kind of input, and then checking what's
actually entered, until the user gets it right
- Given a problem and initial data, keep refining
your solution to the problem until an acceptable
level of accuracy is obtained
The for loop
Version 1 (when the body of the loop is one statement)
- for (initialization ; logical expression; update expression)
statement1;
Version 2 (when the body of the loop is a block of statements)
- for (initialization ; logical expression; update expression) {
statement a; // Two or more statements between { }'s
statement b; // comprise a block of statements
statement c;
}
- The three parts of the for statement, the initialization statement,
the logical expression, and the update expression, determine the
loop actions.
- In the initialization statement, a variable
(often referred to a the counter variable) is initialized.
- In the second part of the for loop, a logical expression is
evaluated. If the logical expression is TRUE, the body of the loop are
is executed.
- Finally, in the update expression, the counter
variable is updated and the process returns to the logical expression
part of the loop. (The initialization in a loop takes place only once when
the program enters the loop.)
Operators for Performing Shortcuts
- C++ provides two special-purpose operators, ++ and - -, which are
often used in the update expression part of the for loop.
- ++variable increments a variable by 1
- --variable decrements a variable by 1
- You will also use these operators written as a suffix, variable++
- In the summing program above, the for loop could be written as:
for (int i = 1; i <= 100; ++i) // ++i is the same as i=i+1
sumSoFar = sumSoFar + i;
Examples
Here are some examples of simple for loops with different loop
parameters. In each case notice that the counter variable of
the loop is declared in the for statement. In C++ common
practice is to declare variables close to their first use, though
technically the loop variables could be declared anywhere before the
entry into the loop.
- // Program fragment Output
// Loop #1
for(int k = 5; k < 7; ++k) 5 6
cout << k << " ";
cout << endl;
// Loop #2
for(int k = 50; k <= 56; k = k + 2) 50 52 54 56
cout << k << " ";
cout << endl;
// Loop #3
for(int k = -5; k < 0; ++k) 5 -4 -3 -2 -1
cout << k << " ";
cout << endl;
The while loop
For some problems the number of times the body of a loop would be
executed is not known in advance, or depends only on the truth value
of a logical expression. In such cases the C++ programmer can use a
while loop.
Version 1 (one statement in loop body)
- while (logical expression)
statement;
Version 2 (more than one statement in loop body)
- while (logical expression) {
statement a; // Two or more statements between {}'s
statement b; // comprise a block of statements
statement c;
}
A while loop will begin by checking to see if the logical
expression is true. It the logical expression is true the body of the
loop will be executed, and then the logical expression will be checked
again and if the logical expression is true the body of the loop will
be executed again. This will continue until the value of the logical
expression turns up false, at which time the loop body will not be
executed - control will pass to the statement following the while
loop.
Example:
x = 1;
while (x != 0) {
cout << "enter an integer, (0 to quit)\n";
cin >> x;
if (x > 0) cout "x squared is " << x*x << "\n";
}
The do while loop
The do while loop is different from the for loop and the while
loop, in that the logical expression is evaluated at the end of the
loop rather than when the loop is entered. For practical purposes,
this means that the do while loop is guaranteed to execute at least
once. The do while loop has the following form:
- do
statement;
while (logical expression);
The statement is executed and the, if the logical expression is
false, control passes to the next statement after the while statement.
If the logical expression is true, control passes back to the do
statement again.
The do while loop is rare compared to the for and the while loop,
but one place such a loop makes sense is one which solicits user
input. For instance, suppose I am writing a very primitive word
processor that detects periods and automatically prints three spaces
before the next sentence. A loop to do that might look like the
following fragment:
- // Fragment of code to detect a period
char aCharacter;
do { // Start loop, execute body as long as...
cin >> aCharacter;
cout << endl << aCharacter;
} while (aCharacter != '.'); // the expression in the while statement
// is true
for (j = 1; j <= 3; j = j + 1)
cout << " " << endl; // Print three spaces
This loop continually asks for a character from the standard input
device and prints it to the standard output device, as long as the
character is not a period. In the event a period is extracted from the
input stream, the period and three spaces are printed.
Exercises
In each of the following exercises you should
assume all variables have been correctly declared previous to the
fragment you are analyzing, and that the proper header files have been
included.
- What would be printed by the following two loops?
a) for (int j; j<5; ++j)
cout << "j= " << j << endl;
b) int j=5;
do {
cout << "j= " << j << endl;
++j;
} while (j<5);
- Give the output in each of the following loops.
a) for (int k=0; k<5; ++k) {
int j = k%2; // % is the modulus operator, the remainder of
// k divided by 2 in this case
if (j==0)
cout << "k modulus 2 = 0, " << "j= " << j << endl;
if (j==1)
cout << "k modulus 2 = 1, " << "j= " << j << endl;
if (j==2)
cout << "k modulus 2 = 2, " << "j= " << j << endl;
}
b) int m=1;
int k=5;
while (k>1) {
k = 10 % m; // k equals the remainder of 10 divided by m
switch (k)
{
case 0:
cout << "Physics is fun" << endl;
break;
case 1:
cout << "Chemistry is fun" << endl;
break;
case 2:
cout << "Math is fun" << endl; //Notice, no break.
default:
cout << "in fact, ALL science is fun, fun, fun!" << endl;
break;
}
m = m + 1; // ++m; could have been used
}
c) int n=9;
float k;
do {
k = pow(n, 2.0); // k equal n raised to the second power
n = n-1; // --n could have been used
cout << "k= " << k << "; n = " << n << endl;
} while (k>30);
solution
- Write simple loops (you do not need to write the whole program) to
print each of the following sequences of numbers.
- 1, 3, 5, 7, 9
- 100, 90, 80, 70, 60, 50
- 1, 4, 9, 16, 25
solution
- Write a program using a simple do-while loop to
print the numbers 1 through 10.
solution