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.

Chapter 7 ■ Functions

Using factorial, we can write a function, combinations, which, given n and r, returns the

number of combinations of n objects taken r at a time. Here it is:

int combinations(int n, int r) {

int factorial(int);

return factorial(n) / (factorial(n-r) * factorial(r));

} //end combinations

The body consists of the function prototype for factorial and one return statement with 3

calls to factorial.

We note, in passing, that this is perhaps the easiest, but not the most efficient, way to evaluate

n

C r

. For instance, if we were calculating 7 C 3

by hand, we would use:

rather than

765 ..

321 ..

7654321 ......

4321321 ......

that the function uses. As an exercise, write an efficient function for evaluating combinations.

To show the functions factorial and combinations in a complete program and to show

how they may be used, we write a program to read values for n and r and print the number of

combinations we can get from n objects taken r at a time.

Program P7.8 shows how it’s done.

Program P7.8

#include <stdio.h>

int main() {

int n, r, nCr, factorial(int), combinations(int, int);

printf("Enter values for n and r: ");

scanf("%d %d", &n, &r);

while (n != 0) {

nCr = combinations(n, r);

if (nCr == 1)

printf("There is 1 combination of %d objects taken "

"%d at a time\n\n", n, r);

else

printf("There are %d combinations of %d objects taken "

"%d at a time\n\n", nCr, n, r);

printf("Enter values for n and r: ");

scanf("%d %d", &n, &r);

}

} //end main

183

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!