08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 7 ■ Functions

A sample run of this program is shown here:

Enter a positive whole number: 4

4! = 24

We now consider the problem of writing a function (which we will call factorial) that, given

an integer n, calculates and returns the value of n!. Since n! is an integer, the “return type” of the

function is int.

We first write the function header. It is

int factorial(int n)

It is interesting to note that the function header is all the information we need in order to use

the function correctly. Ignoring for the moment what the rest of factorial might look like, we can

use it like this:

printf("5! = %d\n", factorial(5));

or like this:

scanf("%d", &num);

printf("%d! = %d\n", num,factorial(num));

4! = 24

In the latter case, if num is 4, printf prints:

The call factorial(num) returns the value 24 directly to the printf statement.

Following the logic of Program P7.6, we write the function factorial as follows:

int factorial(int n) {

int nfac = 1;

for (int h = 2; h <= n; h++)

nfac = nfac * h;

return nfac;

} //end factorial

It is worthwhile comparing Program P7.6 and the function:

• The program prompts for and reads a value for n; the function gets a value

for n when the function is called, as in factorial(4). It is wrong to attempt

to read a value for n in this function.

• In addition to n, both the program and the function need the variables nfac

and h to express their logic.

179

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!