08.01.2023 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

7.7.1 Using Factorial

Chapter 7 ■ Functions

We illustrate how factorial can be used by writing a complete Program P7.7, which prints n!

for n = 0, 1, 2, 3, 4, 5, 6 and 7.

Program P7.7

#include <stdio.h>

int main() {

int factorial(int);

printf(" n n!\n\n");

for (int n = 0; n <= 7; n++)

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

} //end main

int factorial(int n) {

int nfac = 1;

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

nfac = nfac * h;

return nfac;

} //end factorial

When run, this program prints the following:

n n!

0 1

1 1

2 2

3 6

4 24

5 120

6 720

7 5040

As you can see, the value of factorial increases very quickly. Even 8! = 40320, which is too big

to fit in a 16-bit integer (largest value that can be stored is 32767). As an exercise, write the loop

from 0 to 8 and see what happens.

Let us take a closer look at main. The first statement is the function prototype for factorial.

This is needed since factorial will be called from main.

181

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!