| |
Main Menu | Next Section |
| Section III : Iteration | Section I: Variables | Section II: Our First Program | Section IV: Branch Statements |
So far we have looked at code that is executed once and in sequential order. In other words, no line of code was executed more than once and the first instruction was executed first, the second, second etc. However, almost all programs out in the real world are more complex, with some code being executed over and over again many times and with various tests to determine if this code or that code is executed. It's time to look at the C++ instructions that allow such non-sequential processing. First, one type of loop.
A. The While Loop
A loop is a section of code that is executed over and over, usually
until some stopping condition is met. You experience this all the time
in life:
C++ offers a number of loop constructs. We shall start with one, the while loop. Here is a simple example that reads in 10 numbers and adds them up:
// A program to add up 10 numbers entered by a user
// File: ch2prg4.cpp
#include <iostream.h>
void main()
// Purpose: to add up 10 numbers entered by a user
// Inputs: 10 numbers
// Returns: NONE
{
int number;
int sum = 0; // initialize the sum to 0
int count = 0; // initialize the counter to 0
while (count < 10)
{ cout << "Please enter a number ";
cin >> number;
sum += number;
count++;
}
cout << "The sum is: " << sum;
}
As usual, there is a lot of new material here so let's wade into it. Since
our focus is the while loop we will start with the line:
Here are some things you want to notice:
Every instruction inside the brackets is part of the while loop - just as every instruction inside the curly brackets associated with 'main' is part of main. Note then that there are two sets of curly brackets in this code, or two blocks of code. One block includes all of 'main'; the other includes only those instructions in the while loop. This second block is inside of (or nested in) the first block. 'Nested' code is a common element in more complex programs.
Have you guessed yet how this code knows to execute exactly 10 times? Take a moment to try and figure it out. Hint: the key is in the code fragment
The code after the word 'while' and in parenthesis is always the test condition. In this case, the test is:
If the answer is yes, the lines inside the while loop are executed. If not, the computer skips to the first instruction after the while loop - the first instruction after the right curly bracket that matches the left curly bracket that began the 'while' statement. In this case, the instruction after the loop is the one that outputs the sum.
Let's explore further what happens when the answer is yes, that is, when the condition test is true and the computer executes the instructions inside the while loop. The first two lines inside the while loop are already familiar to us - the user is asked for a number and the computer waits until one is entered, then the computer stores the value entered into the memory location symbolized by the variable 'number'.
The purpose of the next line:
is to add the value stored in 'number' to the value stored in 'sum' The '+=' operator is short-hand for addition followed by assignment. Thus the code could have been written as:
C++ programmers are lazy and don't like to type more than they absolutely have to so C++ is filled with such short-hand. In either case the semantics is:
Back to the code: The purpose of the line:
is to increment by 1 the counter that keeps track of how many numbers have been entered. This is really short-hand for:
So, the first time through the loop, the user is asked to enter a number, the value entered is stored in number, the value is then added to the value already stored in sum and the value in counter is incremented by 1.
OK, so now we have gone through the loop once and our focus is on the right curly bracket at the bottom of the loop. (Be honest, did you know that was where your focus was?) What does the computer do at this point?
Since this is a loop, the computer returns to the top of the loop - back to the line:
Again, the test condition is examined. This time 'count' has the value
1 since it was initialized to 0 in the line
and it has been incremented by 1 in the line
Therefore,
the test
is still true and the computer will again execute the instructions inside the loop. This will continue until 'count' has the value '10'. At this point the test, "count' < 10", will fail and the computer will skip to the first instruction after the while loop. In other words, the line:
will be executed.
The test condition will have been tested eleven times. The first ten times the test result will be true and the code inside the curly brackets will be executed. On the eleventh pass, the test will be false and the loop will end.
It is now time to see why the code includes the two initialization lines:
Earlier, we discussed the fact that when a variable is declared, the memory location corresponding to that variable contains garbage. This is true unless the code explicitly says otherwise through an initialization. Now, consider the counter. What should be the value of the counter when we start? Zero, of course! Thus we use the code:
which both declares the variable 'counter' and gives it the initial value zero. We could have made this two lines:
but, hey, anything to save some typing!
Consider what would happen if we failed to initialize this variable, that is, if we left off the '= 0' part of the line. In this case, the variable 'counter' has some value but we do not know what it is. Suppose that the last time this memory location was used, it was left with the value '-9'. Now, when we go through the loop the first time and increment the counter, it has the value '-8' (-9 + 1) not '1' which is what it should have.
A similar argument can be made for the variable 'sum'. It should start with the value '0' but if we do not include '=0' in the initialization line, 'sum' has some unknown value. Perhaps that value is '102'. If the user enters the value '10' the first time through the loop, the value in sum at the bottom of the loop will be '112' (102 + 10), not simply '10'. If these last few paragraphs are not clear, consider compiling and running the demo program ch2prg4.cpp
B. Tracing
If you really want to learn how to program, you need to read lots of
other people's code. And, to truly be able to take advantage of the code you read, you need to understand exactly how it works. One way to understand
code is to trace it. Each programmer has his or her own way of doing
a 'trace' Here, we give one approach.
First, determine how many variables there are in the code fragment you are interested in. (Usually one does not trace a whole program - just that part of the program of specific interest.) For each such variable create a column on a piece of paper and label the column with the name of the variable. Each column will represent the 'history' of the values of one variable so right underneath the column name put the value that variable was initialized to or a '?' to indicate the value is unknown, meaning garbage. Our little program (It's so small that the whole program can be considered a code fragment.) has three variables so we create the three columns:
| number | sum | count |
| ? | 0 | 0 |
The first line of code is the 'while test' so we look in the 'count' column to see if 'count' is less than 10. It is so we (acting as the computer) go inside the while loop. The user is asked for a number and types in '12 - according to our example above. In the column labeled 'number' we write '12' to indicate that the variable 'number' now has a 12 in it.
| number | sum | count |
| ? | 0 | 0 |
| 12 |
| number | sum | count |
| ? | 0 | 0 |
| 12 | 12 | 1 |
| number | sum | count |
| ? | 0 | 0 |
| 12 | 12 | 1 |
| 4 | 16 | 2 |
Again the code returns to the top of the loop and again 'count' is less than 10 so the loop is re-entered. This time the user enters 3, the sum becomes 19 and 'count' becomes 3:
| number | sum | count |
| ? | 0 | 0 |
| 12 | 12 | 1 |
| 4 | 16 | 2 |
| 3 | 19 | 3 |
| number | sum | count |
| ? | 0 | 0 |
| 12 | 12 | 1 |
| 4 | 16 | 2 |
| 3 | 19 | 3 |
| 5 | 24 | 4 |
| 7 | 31 | 5 |
| 6 | 37 | 6 |
| 8 | 45 | 7 |
| 7 | 52 | 8 |
| 10 | 62 | 9 |
| number | sum | count |
| ? | 0 | 0 |
| 12 | 12 | 1 |
| 4 | 16 | 2 |
| 3 | 19 | 3 |
| number | sum | count |
| ? | 0 | 0 |
| 12 | 12 | 1 |
| 4 | 16 | 2 |
| 3 | 19 | 3 |
| 5 | 24 | 4 |
| 7 | 31 | 5 |
| 6 | 37 | 6 |
| 8 | 45 | 7 |
| 7 | 52 | 8 |
| 10 | 62 | 9 |
| 2 | 64 | 10 |
// A program to calculate a simple salary for 10 hourly employees
// File: ch2prg5.cpp
#include <iostream.h>
void main()
// Purpose: to calculate and output a simple salary for 10 employees
// having input for each employee their rate of
// pay and hours worked
// Receives: NONE
// Returns: NONE
{
double rateOfPay;
double salary; // variables involving money should be
// declared as doubles.
double hoursWorked; // can be a fraction of an hour
int count = 0; // initialize the counter to 0
while (count < 10)
{
cout << "Please enter your rate of pay ";
cin >> rateOfPay;
cout << "Please enter the hours you worked this week ";
cin >> hoursWorked;
salary = hoursWorked * rateOfPay;
cout << "Your salary is: " << salary << endl;
count++;
}
}
A couple of minor points about this code: First, notice all the comments. It is wise to use comments to explain any part of the program that could be at all unclear. Second, we have been skipping the 'endl' in many of our programs because the programs only output one value. Here we must include it in the line that outputs the salary or the request for the next employee's rate of pay will appear on the same line as the output of the previous employee's salary.
| |
Main Menu | Next Section |