C++ Program to Calculate Factorial of a number

Question

Write a C++ program that calculates the factorial of a number using a function. The Program should use a While Loop. The program prompts the user to enter an integer from the standard input, calculates and displays the factorial of the inputed number. Draw the Flowchart

 

Answer

The factorial of a number is obtained by continuously multiplying the number with lower integers in steps of 1.

Fatorial of n is given by

Factorial n = n * (n-1) * (n-2) *… * 2 * 1

Factorial 5 = 5 *4 * 3 * 2 * 1 = 120

 

Flowchart is given below

For the decision, the control continues downwards for NO and branches to the right for YES

 

C++ Program is given below

//Functions computes the factorial of a number
//By Kindson Munonye
//Date: February 2013
//Date Modified: February 2013
//Location: Port Harcourt, Nigeria
#include ;
#include ;

using namespace std;

int factorial(int n)
{
int fact = 1;
while(n<1) {
fact = fact * n;
n--;
}
return fact;
}

int main()
{
int num;
cout<<"Enter an integer: "; cin>>num;
cout<<"\n\n Factorial "<<num<<" = "<<factorial(num)<<endl;
system("pause");
return 0;
}