The source code to calculate the factorial of a given number using recursion is given below. The given program is compiled and executed successfully.
# Ruby program to calculate the factorial
# using the recursion
def factorial(num)
if num == 1
return 1;
else
return num * factorial(num-1);
end
end
print "Enter number: ";
num = gets.chomp.to_i;
fact = factorial(num);
print "Factorial is: ",fact;
Output:
Enter number: 5
Factorial is: 120
Explanation:
In the above program, we created a recursive function factorial(). Here, we read an integer number from the user and passed it to the factorial() function and got the factorial of a specified number and printed the result.
Program/Source Code:
The source code to calculate the factorial of a given number using recursion is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created a recursive function factorial(). Here, we read an integer number from the user and passed it to the factorial() function and got the factorial of a specified number and printed the result.
need an explanation for this answer? contact us directly to get an explanation for this answer