Ruby program to find the sum of the digits of a given number using recursion

Ruby Example: Write a program to find the sum of the digits 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 sum of the digits of the input number using recursion.

Program/Source Code:

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

# Ruby program to find the sum the digits 
# of given number using recursion

def SumOfDigits(num,sum)
	if num > 0 
		sum += (num % 10);
		SumOfDigits(num / 10,sum);
	else
	    return sum;    
	end
end

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

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

Output:

Enter number: 2365
Result is: 16

Explanation:

In the above program, we read an integer number from the user. Then we calculated the sum of digits of the input number using the recursive function SumOfDigits(). Then we printed the result.

Ruby User-defined Functions Programs »




Comments and Discussions!

Load comments ↻





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