Computer Labs homework
C++ Loops
General Discussion of Loops
A loop is a programming construct that allows a group of statements, called the loop body, to be executed zero or more times. For example, a loop might cause a group of statements to be executed 12 times.
A loop is controlled in part by the loop continuation condition. As long as the loop continuation condition remains true, the loop will continue to execute. In order for a loop to stop, it must have a terminating action, i.e. statement(s) in the loop body which when executed insure that the continuation condition will eventually become false.
A loop control variable is a variable whose change may cause the continuation condition to become false. A common error is to not initialize the control variable. To help ensure that the loop does not become an infinite loop, always make sure to do the following three things with the LCV (loop control variable):
1) Initialize the LCV, almost always done before the loop. 2) Test the LCV, this is done inside the continuation condition. 3) Update or change the LCV, inside the loop body.
There are three kinds of loops that are commonly available in programming languages. 1) The while loop executes an indefinite and possibly zero number of repetitions. 2) The do-while loop executes an indefinite number of times, but always at least once. 3) The for loop is convenient when the number of repetitions is known in advance.
C++ Loops
The above three loop types are available in C and C++, but the while loop is the most often used; lets see some examples.
Example 1: A while loop that determines the number of digits in a positive integer, N. Assume that N has previously been declared and given a value.
int Copy = N; // don’t want to destroy N!
DigitCount = 1; // all numbers have at least 1 digit while ( Copy >= 10) // count the rest of the digits { ++DigitCount; // found one more digit Copy /= 10; // get rid of rightmost digit }
When the loop finishes, DigitCount holds the number of digits in the integer N.
Example 2: A do-while loop that determines the number of digits in integer, N, same as above.
int Copy = N; // don’t destroy original N
DigitCount = 0; // do-while loop will increment this at least once do { ++DigitCount; // found one more digit Copy /= 10; // get rid of rightmost digit } while ( Copy != 0); // count the rest of the digits. Note the ‘;’
A for loop could also be used to count digits, but let’s instead look at an example more suited to the strong points of the for loop.
Example 3: A loop to print all of the upper case letters.
char Ch; for ( Ch = ‘A’; Ch <= ‘Z’; ++Ch ) cout << Ch;
This loop is equivalent to the following while loop:
char Ch; Ch = ‘A’; while ( Ch <= ‘Z’ ) { cout << Ch; ++Ch; }
The following rules are used by C++ when executing for loops: a) The code preceding the first semicolon is executed once, before the loop is entered. b) The condition, which is between the first and second semicolons, is checked. If it is false,
the loop is ended. If the condition is true, the statement(s) in the loop body are executed. c) The action that follows the second semicolon is taken, again after the loop body statements
are done. d) Step b) is repeated.
It is not difficult to see that a for loop is a “repackaged” while loop. Note that the for loop code is more compact, and is not always easily read as the equivalent while loop.
Choosing a Loop
Following the rules below will lead to code that is easier to write and read:
If the number of loop repetitions is known in advance, favor the for loop.
If the number of loop repetitions is NOT known in advance, but may be zero, favor the while loop.
If the number of loop repetitions is NOT known in advance, but is at least 1, favor the do-while loop.
Avoid temptations to always use a for loop, because it leads to more compact code!
Exercise: What would be the loop of choice in writing the following code? 1) Code to print the numbers from 1 to 100. 2) Code that requires the user press the enter key to continue.
The answer to 1) is clearly a for loop. The code below displays the numbers from 1 to 100 in rows that each has 10 numbers. Note that control variable can be declared via the initial for loop statement.
for ( int N = 1; N <= 100; ++ N ) { cout << setw(4) << N; if ( N % 10 == 0 ) cout << endl;
}
The answer to 2) would seem to be the do-while loop, since we need to read at least one char. Indeed, the following loop works:
do {
cout << “Press Enter key to continue: “; cin.get(Ch);
} while ( Ch != ‘\n’ );
The only problem with the do-while loop above is the monotonous user message. So many programmers might prefer the while loop below.
cout << “Press Enter key to continue: “; cin.get(Ch); // priming read
while ( Ch != ‘\n’ ) {
cout << “You pressed “ << Ch << “ You must press Enter to continue: “; cin.get(Ch);
}
The code above is a few lines longer, but gives a better message. It also is typical of a common loop technique, i.e.
get first item, N while N is not equal to stop value {
<loop statements> get next item, N }