# Ruby program to calculate the factorial of given number using recursion

Ruby Example: Write a program to calculate the factorial of given number using recursion.
Submitted by Nidhi, on December 24, 2021

Problem Solution:

In this program, we will create a recursive function to calculate the factorial of a specified number and return 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.

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

Preparation

What's New

Top Interview Coding Problems/Challenges!