15.5k views
5 votes
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.

User Coolwater
by
5.1k points

1 Answer

3 votes

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. if(n <= 7){
  16. cout<<"Factorial is "<< factorial(n);
  17. }else{
  18. cout<<"Wrong input number.";
  19. }
  20. return 0;
  21. }

Step-by-step 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.

User Vladimir Kishlaly
by
5.0k points