UMBC CS 201, Spring 99
 UMBC CMSC 201 Spring '99 CSEE | 201 | 201 S'99 | lectures | news | help

# n choose k

How many ways can you pick k items out of a set of n items?

```                    n!
----------
k!*(n-k)!
```

## The Program

/* * File: combine.c * --------------- * This program tests a function to compute the * mathematical combination function * Combinations(n, k), which gives the number * of ways to choose a subset of k objects from * a set of n distinct objects. */ #include <stdio.h> /* Function prototypes */ int Combinations (int n, int k); int Factorial (int n); /* Main program */ main () { int n, k; printf("Enter number of objects in the set (n)? "); scanf ("%d", &n); printf("Enter number to be chosen (k)? "); scanf ("%d", &k); printf("C(%d, %d) = %d\n", n, k, Combinations(n, k)); } /* * Function: Combinations * Usage: ways = Combinations(n, k); * --------------------------------- * Implements the Combinations function, which * returns the number of distinct ways of choosing * k objects from a set of n objects. In * mathematics, this function is often written as * C(n,k), but a function called C is not very * self-descriptive, particularly in a language * which has precisely the same name. Implements * the formula n!/(k! * (n - k)!) */ int Combinations(int n, int k) { int numerator, denominator, ways; numerator = Factorial (n); denominator = Factorial (k) * Factorial (n - k); ways = numerator / denominator; return (ways); } /* * Function: Factorial * Usage: f = Factorial(n); * ------------------------ * Returns the factorial of the argument n, where * factorial is defined as the product of all * integers from 1 up to n. */ int Factorial (int n) { int product, i; product = 1; for (i = 1; i <= n; i++) { product *= i; } return (product); }

## The Sample Run

lassie% a.out Enter number of objects in the set (n)? 6 Enter number to be chosen (k)? 2 C(6, 2) = 15 lassie% lassie% a.out Enter number of objects in the set (n)? 3 Enter number to be chosen (k)? 2 C(3, 2) = 3 lassie% lassie% a.out Enter number of objects in the set (n)? 12 Enter number to be chosen (k)? 4 C(12, 4) = 495 lassie% exit lassie%

## The Lesson

• Functions can contain calls to other functions
• Statistical combination - n choose k

CSEE | 201 | 201 S'99 | lectures | news | help

Wednesday, 17-Feb-1999 14:03:42 EST