0% found this document useful (0 votes)
6 views14 pages

Comp 1601 - More About Functions Notes

Uploaded by

vc89bq2c6x
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views14 pages

Comp 1601 - More About Functions Notes

Uploaded by

vc89bq2c6x
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

14.

Some More Things About Functions

This chapter presents some more information about functions. It starts by looking at the main part of
the programs we have been writing. Next, it explains that functions must be declared before they are
used and shows how this is done. The need for the #include statement, used in all our programs so far,
is then explained. Finally, the interesting concept of recursion is discussed, where a function calls itself.

14.1 What is main?

All the programs we have been writing so far have a part called main. Let us look closely at the structure
of the main part of a program. Consider the main part of the program which calls the sum1toN()
function from Chapter 13 twice. The first time, the function is called with the parameter 5 and the
second time, it is called with the parameter 10. The analysis of the main part is given in Figure 14.1.

name of function
formal parameter
return type
list (empty)

int main () {

sum1toN(5);

cout << endl; “body” of function

sum1toN(10);

return 0;
}

return value of 0 (type


corresponds to return type)

Figure 14.1: Analysis of the Main Part of a Program

From Figure 14.1, it can be observed that the main part of the programs we have written so far is really
a function with an empty parameter list. So, it should be properly called the main() function. The name
of the function, main, is special. By convention, whenever a C++ program is run, the main() function is
the first one to be executed. The main() function can call other functions to get its job done. For
example, it can call functions such as drawRectangle() and sum1toN().

1
14.2 Declaring Functions

Consider the program consisting of the sum1toN() function from Chapter 13 and the main() function
from Figure 14.1.

#include <iostream>

using namespace std;

void sum1toN(int n) {

int i;
int sum;

sum = 0;

for (i=1; i<=n; i=i+1) {


sum = sum + i;
}

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


}

int main () {

sum1toN(5);

cout << endl;

sum1toN(10);

return 0;
}

So far, we have been writing our functions above the main() function in the file containing the source
code. Unless a function is written in the source code above the place where it is called, the function
must be declared. The sum1toN() function can be declared as follows:

void sum1toN(int n);

The declaration consists of the return type of the function (in this case, void), the name of the function
(sum1toN), followed by the parameter list in parentheses, followed by a semi-colon.

2
If a function is declared before it is used, it can be written anywhere in the source code. For example, it
can be written below the main() function or even in another file (which is beyond the scope of this
book).

In the following example, the sum1toN() function is declared before it is called in main() but it is written
after main() in the source code.

#include <iostream>

using namespace std;

void sum1toN(int n); // declaration of sum1toN() function

int main () {

sum1toN(5);

cout << endl;

sum1toN(10);

return 0;
}

void sum1toN(int n) {

int i;
int sum;

sum = 0;

for (i=1; i<=n; i=i+1) {


sum = sum + i;
}

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


}

3
14.3 The #include Statement

Function declarations for a set of related functions can be placed in a file called a header file and the
contents of the header file can be read and copied into a program using the #include statement. For
example, the following statement causes the function declarations for functions such as ceil(), floor(),
sqrt(), sin(), cos(), etc. to be automatically inserted into a program before it is compiled.

#include <cmath>

Since the function declarations are now available to the compiler, you can call these functions without
writing the declarations at the top of the source code.

The #include statement only inserts the function declarations into a source file when it is being
compiled. The code for the actual functions may have been previously compiled and stored in a code
library. The functions can also be written in the same source file or in another source file. If a code
library is used, the compiled functions are automatically “joined” (or linked) to the executable program
if compilation is successful. For example, all the functions in the cmath code library are inserted in the
executable program if compilation is successful. Functions from different code libraries can be used in
the same program if there is an #include statement for each code library.

14.4 Recursive Functions

So far, we have seen how the main() function can call the drawRectangle() and sum1toN() functions as
well as other functions such as ceil() and floor(). Since main() is a function, this indicates that any
function can call one or more functions.

Suppose we wanted to write a function, printStars(), which displays a certain number of asterisks on the
monitor. The function should accept an integer parameter n and then display n asterisks on the monitor
using a for loop. The printStars() function can be written as follows:

4
void printStars (int n) {
int i;

for (i=1; i<=n; i=i+1) {


cout << "*";
}
}

The function can be called whenever we need to display a certain number of asterisks on the monitor.
For example, if we want to display 10 asterisks, the printStars() function can be called as follows:

printStars (10);

The problem of displaying n asterisks on the monitor can be viewed in a different way, as shown in the
following pseudocode:

printStars (int n):


if n is equal to zero
Stop. There is nothing to do.
otherwise {
Display one asterisk on the monitor.
Display the remaining asterisks on the monitor.
}

Displaying one asterisk on the monitor is easy:

cout << "*";

To display the remaining asterisks on the monitor, we need to know how many more must be displayed.
If 10 asterisks were initially required, after displaying one, 9 more must be displayed. In general, if n
asterisks are required, after displaying one, (n – 1) more asterisks must be displayed.

How can the remaining (n – 1) asterisks be displayed? We can call the same function, printStars(), with
(n – 1) as the parameter. The printStars() function can now be written as follows:

5
void printStars (int n) {

if (n == 0) // Stop. There is nothing to do.


return;
else {
cout << "*"; // Display one asterisk on the monitor.
printStars (n - 1); // Display the remaining asterisks on the monitor.
}
}

This version of the printStars() function produces the same results as the previous version. Yet, it does
not contain a loop. It is a recursive function, i.e., a function that calls itself.

Recursive functions normally have two parts. One part is used to stop the recursion so that the function
will stop calling itself (if this is not done, the function will usually keep calling itself without stopping).
This part is called the base case. In the function above, the base case is:

if (n == 0) // Stop. There is nothing to do.


return;

The second part of a recursive function is called the recursive case. This is where the function calls itself,
usually with an actual parameter with a smaller value. In the example above, the recursive case is:

printStars (n - 1); // Display the remaining asterisks on the monitor.

It should be noted that a recursive function is called in the same manner as a non-recursive function. So,
to call the recursive version of the printStars() function to display 10 asterisks on the monitor, the
following statement is required:

printStars (10);

14.5 Recursion Tree

Figure 14.2 is a recursion tree for the printStars() function when n is 10. It shows what is involved in
executing the call to printStars (10). On the first call to the printStars() function, since n is not zero, one
asterisk is displayed and the function is called recursively with the actual parameter, 9. This is the
second call to the printStars() function. Since n is not zero, one asterisk is displayed and the function is

6
called recursively with the actual parameter, 8. This continues until the printStars() function is called
with the actual parameter, 0. This is the eleventh call to the printStars() function. Since n is zero, the
function returns without doing anything. Another recursive call is not made. This causes all the other
function calls to terminate, one at a time until the original call to printStars(10) is completed. It should
be noted that the final output consists of one line containing 10 asterisks.

Figure 14.2: Recursion Tree for printStars() Function

7
14.6 Recursive Version of Printing a Sequence

Consider the following function, printSequence, which accepts an integer n as a parameter and displays
all the values from n to 1 on the monitor, one per line:

void printSequence (int n) {

int i;

for (i=n; i>=1; i=i-1)


cout << i << endl;

The problem of displaying the sequence of numbers on the monitor from n to 1 can be viewed in a
different way, as shown in the following pseudocode:

printSequence (int n):


if n is equal to zero
Stop. There is nothing to do.
otherwise {
Display the value of n on the monitor.
Display the values of the sequence n-1 to 1 on the monitor.
}

Displaying the value of n on the monitor is easy:

cout << n << endl;

To display the values of the sequence n-1 to 1 on the monitor, we can call the same function,
printSequence(), with (n – 1) as the parameter. The printSequence() function can now be written as
follows:

void printSequence (int n) {

if (n == 0) // Stop. There is nothing to do.


return;
else {
cout << n << endl; // Display the value of n on the monitor.
printSequence (n - 1); // Display sequence n-1 to 1 on the monitor.
}
}

8
This version of the printSequence() function produces the same results as the previous version. The
recursion tree for the printSequence() function when n is 10 is shown in Figure 14.3. It should be noted
that the final output consists of 10 lines, each line containing a single number from 10 to 1.

Figure 14.3: Recursion Tree for printSequence() Function

9
14.7 Recursive Version of the sum1toN() Function

Let’s look again at the sum1toN() function given in the previous chapter:

int sum1toN(int n) {

int i;
int sum;

sum = 0;

for (i=1; i<=n; i=i+1) {


sum = sum + i;
}

return sum;
}

The function finds the sum of all the integers between 1 and n, inclusive. If n is 10, it finds the sum of

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10

The sum can be re-written as follows:

10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1

This is the same as:

10 + (sum of all the integers between 1 and 9, inclusive).

In general, to find the sum of all the integers between 1 and n, inclusive, the following recursive
expression can be used:

sum = n + (sum of all the integers between 1 and n – 1, inclusive)

10
Using this expression, the sum1toN() function can be viewed as follows:

sum1toN (int n):


if n is equal to zero
Stop. There is nothing to do. Return 0.
Otherwise {
sum = n + sum of all the integers between 1 and (n – 1).
return sum
}

The function can be written as follows using recursion:

int sum1toN (int n) {

int sum;

if (n == 0) // base case
return 0;
else {
sum = n + sum1toN (n - 1); // recursive case
return sum;
}
}

14.8 Using Recursion to Find the Sum of the Digits of a Positive Integer

Consider the problem of finding the sum of the digits of a positive integer, n. For example, if n is 3687,
the sum of the digits is 24. The problem can be viewed recursively as follows:

sumDigits (int n):

if n has only one digit


Stop. There is nothing to do. Return n. 36,21
otherwise {
sum = last digit + sum of digits in n without last digit.
return sum. 368.7
}

36

11
Now, the last digit of n can be found by using the expression, n % 10. The number obtained from n
which does not contain the last digit can be found by using the expression, n / 10. The function can be
written as follows using recursion:

int sumDigits (int n) {

int sum;

if (n < 10) // base case: n has only 1 digit


return n;
else {
sum = n % 10 + sumDigits (n / 10); // recursive case
return sum;
}
}

14.9 Exercises

int factorial ital


1. The factorial of a positive integer n (written, n!) is defined as follows: int fact

if
n! = n x (n – 1) x (n – 2) …. x 3 x 2 x 1
n o
For example,
5! = 5 x 4 x 3 x 2 x 1 = 120 return 1
else
Write a recursive function, factorial(), which accepts a positive integer n as a parameter and returns
the factorial of n. Note that the factorial of 0 is 1.
fact n factorial n 1

2. If n is a positive integer, the product of p and n can be found by repeatedly adding p to itself, n
times. For example, p x 5 = p + p + p + p + p. Write a recursive function, multiply, based on the
following pseudocode:

multiply (p, n):


if n is equal to 1
Stop. There is nothing to do. Return p.
else {
mult = p + product of p and n – 1.
return mult.
}

3. The printSequence() recursive function in Section 14.6 displays the values in the sequence from n to
1. How can the function be modified to display the values from 1 to n?

12
2 write a recursive multiply function

int multiply int p int n

int product
if n 1

return p

else
muliply p n t
product p
return product

3 Write function thatprints mums from n to 1

void printSequence int n

if n i

cont ca n

enital

else
cont c c n CC
cont

printSequence n 1

You might also like