Q:

Ruby program to calculate the factorial of given number using recursion

belongs to collection: Ruby User-defined Functions Programs

0

In this program, we will create a recursive function to calculate the factorial of a specified number and return the result.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

# 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Ruby User-defined Functions Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Ruby program to print the Fibonacci series using r... >>
<< Ruby program to create a simple recursive function...