C++ 4
C++ 4
The execution of countdown begins with n=2, and since n is not zero,
it outputs the value 2, and then calls itself...
3
2
1
Blastoff!
As a second example, let’s look again at the functions newLine and threeLine.
void newLine () {
cout << endl;
}
void threeLine () {
newLine (); newLine (); newLine ();
}
Although these work, they would not be much help if I wanted to output 2
newlines, or 106. A better alternative would be
main
n: 3 countdown
n: 2 countdown
n: 1 countdown
n: 0 countdown
There is one instance of main and four instances of countdown, each with a
different value for the parameter n. The bottom of the stack, countdown with
n=0 is the base case. It does not make a recursive call, so there are no more
instances of countdown.
The instance of main is empty because main does not have any parameters
40 CHAPTER 4. CONDITIONALS AND RECURSION
4.10 Glossary
modulus: An operator that works on integers and yields the remainder when
one number is divided by another. In C++ it is denoted with a percent
sign (%).
conditional: A block of statements that may or may not be executed depend-
ing on some condition.
recursion: The process of calling the same function you are currently execut-
ing.
infinite recursion: A function that calls itself recursively without every reach-
ing the base case. Eventually an infinite recursion will cause a run-time
error.
Chapter 5
Fruitful functions
But so far all the functions we have written have been void functions; that is,
functions that return no value. When you call a void function, it is typically on
a line by itself, with no assignment:
nLines (3);
countdown (n-1);
In this chapter, we are going to write functions that return things, which I will
refer to as fruitful functions, for want of a better name. The first example is
area, which takes a double as a parameter, and returns the area of a circle with
the given radius:
The first thing you should notice is that the beginning of the function definition
is different. Instead of void, which indicates a void function, we see double,
which indicates that the return value from this function will have type double.
41
42 CHAPTER 5. FRUITFUL FUNCTIONS
Also, notice that the last line is an alternate form of the return statement
that includes a return value. This statement means, “return immediately from
this function and use the following expression as a return value.” The expres-
sion you provide can be arbitrarily complicated, so we could have written this
function more concisely:
On the other hand, temporary variables like area often make debugging easier.
In either case, the type of the expression in the return statement must match
the return type of the function. In other words, when you declare that the return
type is double, you are making a promise that this function will eventually
produce a double. If you try to return with no expression, or an expression
with the wrong type, the compiler will take you to task.
Sometimes it is useful to have multiple return statements, one in each branch
of a conditional:
Since these returns statements are in an alternative conditional, only one will
be executed. Although it is legal to have more than one return statement in a
function, you should keep in mind that as soon as one is executed, the function
terminates without executing any subsequent statements.
Code that appears after a return statement, or any place else where it can
never be executed, is called dead code. Some compilers warn you if part of
your code is dead.
If you put return statements inside a conditional, then you have to guarantee
that every possible path through the program hits a return statement. For
example:
double distance (double x1, double y1, double x2, double y2) {
return 0.0;
}
The return statement is a placekeeper so that the function will compile and
return something, even though it is not the right answer. At this stage the
44 CHAPTER 5. FRUITFUL FUNCTIONS
I chose these values so that the horizontal distance is 3 and the vertical distance
is 4; that way, the result will be 5 (the hypotenuse of a 3-4-5 triangle). When
you are testing a function, it is useful to know the right answer.
Once we have checked the syntax of the function definition, we can start
adding lines of code one at a time. After each incremental change, we recompile
and run the program. That way, at any point we know exactly where the error
must be—in the last line we added.
The next step in the computation is to find the differences x2 −x1 and y2 −y1 .
I will store those values in temporary variables named dx and dy.
double distance (double x1, double y1, double x2, double y2) {
double dx = x2 - x1;
double dy = y2 - y1;
cout << "dx is " << dx << endl;
cout << "dy is " << dy << endl;
return 0.0;
}
I added output statements that will let me check the intermediate values before
proceeding. As I mentioned, I already know that they should be 3.0 and 4.0.
When the function is finished I will remove the output statements. Code
like that is called scaffolding, because it is helpful for building the program,
but it is not part of the final product. Sometimes it is a good idea to keep the
scaffolding around, but comment it out, just in case you need it later.
The next step in the development is to square dx and dy. We could use the
pow function, but it is simpler and faster to just multiply each term by itself.
double distance (double x1, double y1, double x2, double y2) {
double dx = x2 - x1;
double dy = y2 - y1;
double dsquared = dx*dx + dy*dy;
cout << "dsquared is " << dsquared;
return 0.0;
}
Again, I would compile and run the program at this stage and check the inter-
mediate value (which should be 25.0).
Finally, we can use the sqrt function to compute and return the result.
5.3. COMPOSITION 45
double distance (double x1, double y1, double x2, double y2) {
double dx = x2 - x1;
double dy = y2 - y1;
double dsquared = dx*dx + dy*dy;
double result = sqrt (dsquared);
return result;
}
Then in main, we should output and check the value of the result.
As you gain more experience programming, you might find yourself writing
and debugging more than one line at a time. Nevertheless, this incremental
development process can save you a lot of debugging time.
The key aspects of the process are:
• Start with a working program and make small, incremental changes. At
any point, if there is an error, you will know exactly where it is.
• Use temporary variables to hold intermediate values so you can output
and check them.
• Once the program is working, you might want to remove some of the
scaffolding or consolidate multiple statements into compound expressions,
but only if it does not make the program difficult to read.
5.3 Composition
As you should expect by now, once you define a new function, you can use it as
part of an expression, and you can build new functions using existing functions.
For example, what if someone gave you two points, the center of the circle and
a point on the perimeter, and asked for the area of the circle?
Let’s say the center point is stored in the variables xc and yc, and the
perimeter point is in xp and yp. The first step is to find the radius of the circle,
which is the distance between the two points. Fortunately, we have a function,
distance, that does that.
double radius = distance (xc, yc, xp, yp);
The second step is to find the area of a circle with that radius, and return it.
double result = area (radius);
return result;
Wrapping that all up in a function, we get:
double fred (double xc, double yc, double xp, double yp) {
double radius = distance (xc, yc, xp, yp);
double result = area (radius);
return result;
}
46 CHAPTER 5. FRUITFUL FUNCTIONS
The name of this function is fred, which may seem odd. I will explain why in
the next section.
The temporary variables radius and area are useful for development and
debugging, but once the program is working we can make it more concise by
composing the function calls:
double fred (double xc, double yc, double xp, double yp) {
return area (distance (xc, yc, xp, yp));
}
5.4 Overloading
In the previous section you might have noticed that fred and area perform
similar functions—finding the area of a circle—but take different parameters.
For area, we have to provide the radius; for fred we provide two points.
If two functions do the same thing, it is natural to give them the same name.
In other words, it would make more sense if fred were called area.
Having more than one function with the same name, which is called over-
loading, is legal in C++ as long as each version takes different parameters. So
we can go ahead and rename fred:
double area (double xc, double yc, double xp, double yp) {
return area (distance (xc, yc, xp, yp));
}
This looks like a recursive function, but it is not. Actually, this version of area
is calling the other version. When you call an overloaded function, C++ knows
which version you want by looking at the arguments that you provide. If you
write:
C++ goes looking for a function named area that takes a double as an argu-
ment, and so it uses the first version. If you write
you run it. This is a warning sign that for one reason or another you are not
running the version of the program you think you are. To check, stick in an
output statement (it doesn’t matter what it says) and make sure the behavior
of the program changes accordingly.
if (x == 5) {
// do something
}
while (true) {
// loop forever
}
is a standard idiom for a loop that should run forever (or until it reaches a
return or break statement).
bool fred;
fred = true;
bool testResult = false;
The first line is a simple variable declaration; the second line is an assignment,
and the third line is a combination of a declaration and as assignment, called
an initialization.
As I mentioned, the result of a comparison operator is a boolean, so you can
store it in a bool variable
48 CHAPTER 5. FRUITFUL FUNCTIONS
if (evenFlag) {
cout << "n was even when I checked it" << endl;
}
A variable used in this way is called a flag, since it flags the presence or absence
of some condition.
if (x > 0) {
if (x < 10) {
cout << "x is a positive single digit." << endl;
}
}
The first line outputs the value true because 2 is a single-digit number. Un-
fortunately, when C++ outputs bools, it does not display the words true and
false, but rather the integers 1 and 0.1
The second line assigns the value true to bigFlag only if 17 is not a single-
digit number.
The most common use of bool functions is inside conditional statements
if (isSingleDigit (x)) {
cout << "x is little" << endl;
} else {
cout << "x is big" << endl;
}
int main ()
{
return 0;
}
The usual return value from main is 0, which indicates that the program suc-
ceeded at whatever it was supposed to to. If something goes wrong, it is common
to return -1, or some other value that indicates what kind of error occurred.
1 There is a way to fix that using the boolalpha flag, but it is too hideous to mention.
50 CHAPTER 5. FRUITFUL FUNCTIONS
Of course, you might wonder who this value gets returned to, since we never
call main ourselves. It turns out that when the system executes a program,
it starts by calling main in pretty much the same way it calls all the other
functions.
There are even some parameters that are passed to main by the system, but
we are not going to deal with them for a little while.
0! = 1
n! = n · (n − 1)!
(Factorial is usually denoted with the symbol !, which is not to be confused
with the C++ logical operator ! which means NOT.) This definition says that
the factorial of 0 is 1, and the factorial of any other value, n, is n multiplied by
the factorial of n − 1. So 3! is 3 times 2!, which is 2 times 1!, which is 1 times
0!. Putting it all together, we get 3! equal to 3 times 2 times 1 times 1, which
is 6.
If you can write a recursive definition of something, you can usually write a
C++ program to evaluate it. The first step is to decide what the parameters
are for this function, and what the return type is. With a little thought, you
should conclude that factorial takes an integer as a parameter and returns an
integer:
5.10. MORE RECURSION 51
Otherwise, and this is the interesting part, we have to make a recursive call to
find the factorial of n − 1, and then multiply it by n.
If we look at the flow of execution for this program, it is similar to nLines from
the previous chapter. If we call factorial with the value 3:
Since 3 is not zero, we take the second branch and calculate the factorial of
n − 1...
Since 2 is not zero, we take the second branch and calculate the
factorial of n − 1...
The return value (1) gets multiplied by n, which is 2, and the result
is returned.
52 CHAPTER 5. FRUITFUL FUNCTIONS
The return value (2) gets multiplied by n, which is 3, and the result, 6, is
returned to main, or whoever called factorial (3).
Here is what the stack diagram looks like for this sequence of function calls:
main
6
n: 3 recurse: 2 result: 6 factorial
2
n: 2 recurse: 1 result: 2 factorial
1
n: 1 recurse: 1 result: 1 factorial
1 factorial
n: 0
The return values are shown being passed back up the stack.
Notice that in the last instance of factorial, the local variables recurse
and result do not exist because when n=0 the branch that creates them does
not execute.