Exercise:
Write a C++ program that uses a recursive function to find the factorial of a positive number.
Click Here to View the Solution:
#include <iostream>
using namespace std;
int fact(int num);
int main()
{
int num;
cout << "Insert a positive integer: ";
cin >> num;
cout << "Factorial of " << num << " is " << fact(num);
return 0;
}
int fact(int num)
{
if(num > 1)
return num * fact(num - 1);
else
return 1;
}
Click Here to View the Output:
Insert a positive number: 7 Factorial of 7 is 5040
Click Here to View the Explanation:
- A value
num
was requested from the user. - A recursive function
fact ()
is created. Anif
statement is used to put a condition at the beginning of the function. The loop can only be entered if the value ofnum
is greater than 1. num
is multiplied byfact (num - 1)
.- The value of
num
is updated with each iteration because it is a recursive function. The value is decremented by 1. - The multiplication continues until
num < 1
and the loop is terminated. - The output is displayed on the screen.