Question: When you write a function to solve a task, you may break the task into subtasks. Sometimes, one of the subtasks is a smaller version

When you write a function to solve a task, you may break the task into subtasks. Sometimes, one of the subtasks is a smaller version of the same task and can be accomplished by calling itself multiple times. In such cases the function is said to be recursive.
Write a recursive function to calculate the value of n!. Factorial of a number is defined as: n!= n(n-1)(n-2)(n-3)...(2)(1). For example, 4!=4*3*2*1. The n! can be written in terms of (n-1)! as: n!= n*(n-1)!,(n-1)!=(n-1)*(n-2)! and so forth.
Thus, in order to compute n!, we need (n-1)!, to have (n-1)!, we need (n-2)! and so forth. As you may immediately notice, the base case for factorial is 1 because 1!=1. Write a program that uses a recursive function called factorial that takes an integer n as its argument and returns n! to the main.
Sample Output: Red colored texts are user inputs. Other texts are the output of the program.
Enter the number: 4
The factorial of the number is 24.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!