cs1ch2sec3.htm
 

Chapter Two
The Basics of C++ and Program Development

Section III. Branch Statements


Section III : Iteration Section I: Variables Section II: Our First Program Section IV: Branch Statements

  


Table of Contents

Learning C++:
An Index of Entry Points


2. The

of C++

A reference document on the basic elements of C++.



3. The Patterns





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:

"Stir until blended"
"While the nail is still exposed, keep hitting it with the hammer."
"Repeat 10 times"

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:
while (count < 10)

Here are some things you want to notice:

-'while' is all in lower case
-there is no semicolon at the end of the line
-a left curly bracket starts the next line and a right
  curly bracket appears four lines down.

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

(count < 10)

The code after the word 'while' and in parenthesis is always the test condition. In this case, the test is:

Does the memory location symbolized by the variable name 'counter'
contain a value less than 10?

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:

sum += number;

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:

sum = sum + number;

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:

The value in the memory location symbolized by the variable
'number' is added to the value in the memory location symbolized
by the variable 'sum' and the result is stored in the memory
location symbolized by the variable 'sum'.

Back to the code: The purpose of the line:

count++;

is to increment by 1 the counter that keeps track of how many numbers have been entered. This is really short-hand for:

count = count + 1;

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:

while (count < 10)

Again, the test condition is examined. This time 'count' has the value 1 since it was initialized to 0 in the line

int count = 0;

and it has been incremented by 1 in the line

count++;

Therefore, the test

'count' < 10'

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:

cout << "The sum is: " << sum;

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:

int sum = 0; // initialize the sum to 0
int count = 0; // initialize the counter to 0

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:

int count = 0;

which both declares the variable 'counter' and gives it the initial value zero. We could have made this two lines:

int count;
count = 0;

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 
Now we act as if we are the computer and walk through the code. Since this program requires 10 numbers input by some user, we make up 10 numbers. For example:

12,    4,    3,    5,    7,    6,    8,    7,    10,    2

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 
Then 12 is added to sum according to the next instruction so we look under 'sum' and find 0. Since 0 + 12 = 12, we put 12 in the 'sum' column. The next line adds 1 to 'count'. Looking in the 'count' column we find that 'count' contains the value 0 and 0 + 1 = 1, so we put a one in the 'count column:
number  sum  count 
?  0  0 
12  12  1 
Now we go to the top of the loop and do the test again. Since 'count' is still less than 10, we go inside the loop. The user enters 4, the sum is updated to 16 (12 + 4) and the count is incremented. Now the trace looks as follows:
number  sum  count 
?  0  0 
12  12  1 
4  16  2 
(Note that the changes shown here to the trace should have been made as soon as the code indicated a change as opposed to at the end of the loop.)

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 
Below you see the trace after the first nine numbers have been entered. If it does not make sense, consider working through the full trace yourself.
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 
At this point, the computer again returns to the top of the loop and, finding that 'count' is still less than 10, it goes inside the loop once more. The user enters 2, the sum is incremented, and 'count' becomes 10.
number  sum  count 
?  0  0 
12  12  1 
4  16  2 
3  19  3 
Below you see the trace after the first nine numbers have been entered. If it does not make sense, consider working through the full trace yourself.
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 
Once more we return to the top of the loop but this time the test proves to be false because 10 is not less than 10. The computer skips to the first line after the while loop, the value '64' is output as the value of 'sum', and the program stops since there are no more instructions. Thus ends our introduction to loops. We close with a second example - a piece of code to make a simple salary calculation for ten hourly employees:

// 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.
Topics Covered in the "Essentials of C++"
The While Loop
the ++ operator

Examples of Iteration

Top of Section Main Menu Next Section