factorial
The Task
- print a table of numbers and their factorials
- recall that n! = n * (n-1) * (n-2) * ... * 2 * 1
The Program
/***********************************************************
* File: fact.c
* Author: S. Bogar
* Date: 1/1/77
* Section: 0101
* EMail: bogar@cs.umbc.edu
*
* This program includes the Factorial function and
* a test program that prints the factorials of the
* numbers between the limits LOWER and UPPER,
* inclusive.
***************************************************/
#include
/* Constants */
#define LOWER 0
#define UPPER 7
/* Function prototypes */
int Factorial (int n);
/* Main program */
int main()
{
int i;
for (i = LOWER; i <= UPPER; i++)
{
printf("%d! = %5d\n", i, Factorial(i));
}
return 0;
}
/**************************************************
* Function: Factorial()
* Usage: f = Factorial(n);
*
* Finds n!, where n-factorial is defined as the product
* of all integers from 1 up to and including n.
*
* Inputs: integer for calculating n!
* Output: Returns the factorial of the argument n (n!)
***************************************************/
int Factorial (int n)
{
int product, i;
product = 1;
/* finds product of all integers from 1 up to
and including n, where product will finally
hold the value of n! */
for (i = 1; i <= n; i++)
{
product *= i;
}
return (product);
}
The Sample Run
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
The Lesson
- Hey, we seem to have two variables named "i". Don't they
interfere with each other?