ADVERTISEMENT
ADVERTISEMENT

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

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

Problem Solution:

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.

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.

Ruby User-defined Functions Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.