Write a function factorial() that takes a positive integer as a parameter and returns the factorial of that integer. The main function takes an integer n<=7, as input, and utilizes the factorial function to calculate the following series.

Answer :

Answer:

The solution code is written in C++:

  1. #include <iostream>
  2. using namespace std;
  3. int factorial(int n){
  4.    if(n == 1){
  5.        return n;
  6.    }else{
  7.        return n * factorial(n-1);
  8.    }
  9. }
  10. int main()
  11. {
  12.    int n;
  13.    cout<<"Please enter a number <= 7 :";
  14.    cin>>n;
  15.    
  16.    if(n <= 7){
  17.        cout<<"Factorial is "<< factorial(n);
  18.    }else{
  19.        cout<<"Wrong input number.";
  20.    }
  21.    return 0;
  22. }

Explanation:

Firstly, create a function factorial with one input parameter (Line 1).

Next, create an if-else statement to check if input n is 1, just return the end (Line 6-7).

Otherwise, the function should return n multiplied by output of the recursive calling of the function itself (Line 8-9).

In the main program, create variable and prompt user to input number (Line 15 -17).

Next, do the input validation checking to ensure the input n must be equal or less than 7 then only call factorial function to calculate the factorial of n and display the answer (Line 19 - 20). Otherwise, the program shall just display error message.

Other Questions