Ruby program to find the reverse of a given number using recursion

Ruby Example: Write a program to find the reverse of a given number using recursion.
Submitted by Nidhi, on December 25, 2021

Problem Solution:

In this program, we will read an integer number from the user and find the reverse of the input number using recursion.

Program/Source Code:

The source code to find the reverse of a given number using recursion is given below. The given program is compiled and executed successfully.

# Ruby program to find the reverse of 
# given number using recursion

def reverse(num,rev)
	if num > 0 
	    rem = (num % 10);
		rev = rev*10+rem;
		reverse(num / 10,rev);
	else
	    return rev;    
	end
end

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

result = reverse(number, 0);
print "Result is: ",result;

Output:

Enter number: 1234
Result is: 4321

Explanation:

In the above program, we read an integer number from the user. Then we found the reverse of the input number using recursive function reverse(). Then we printed the result.

Ruby User-defined Functions Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.