The C++ Programming Language

Recursive Factorial Example Program


Click below to go directly to a specific section:
Description | Source Code | Sample Run | Program Notes

Description

This program takes a small positive or zero integer value and computes the factorial for that number recursively and displays the result.

Source Code

#include <iostream.h>

int factorial(int);

void main(void) {
	int number;
	
	cout << "Please enter a positive integer: ";
	cin >> number;
	if (number < 0)
		cout << "That is not a positive integer.\n";
	else
		cout << number << " factorial is: " << factorial(number) << endl;
}

int factorial(int number) {
	int temp;

	if(number <= 1) return 1;

	temp = number * factorial(number - 1);
	return temp;
}

Sample Run

Please enter an integer value: 7
7 factorial is: 5040

Program Notes

This program asks the user to input an integer value. The integer is sent to function factorial where it recursively calls itself over and over with the next smallest integer until the number 1 is hit. Once at 1, the values are returned to the previous factorial call and multiplied together. This program has been tested and works for small integers, (due to C++ integer limitations).
[Back] [Home]

Last modified: 04:17 PM on 09/17/1999