Q:

Ruby program to calculate the power of a given number using recursion

belongs to collection: Ruby User-defined Functions Programs

0

In this program, we will read a number and power from the user and calculate the power of the number using recursive function 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 power of a given number using recursion is given below. The given program is compiled and executed successfully.

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

def CalculatePower(num, power)
	result = 1;
	if power > 0 
		result = num * (CalculatePower(num, power-1));
	end
	return result;
end

print "Enter number: ";
number = gets.chomp.to_i;  

print "Enter power: ";
power = gets.chomp.to_i;  

result = CalculatePower(number, power);
print "result: ",result;

Output:

Enter number: 2
Enter power: 3
result: 8

Explanation:

In the above program, we read a number and power from the user and called the created recursive function CalculatePower() function and got the result. Then we 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 count the digits of a given number... >>
<< Ruby program to print the Fibonacci series using r...