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 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 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: 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 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:
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.
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:
|
|