Q:

Ruby program to count the digits of a given number using recursion

belongs to collection: Ruby User-defined Functions Programs

0

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

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 count the digits of a given number using recursion is given below. The given program is compiled and executed successfully.

# Ruby program to count the digits 
# of given number using recursion

def CountDigits(num,count)
	if num > 0 
		CountDigits(num / 10,count+1);
	else
	    return count;    
	end
end

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

result = CountDigits(number, 0);
print "Total digits are: ",result;

Output:

Enter number: 4326
Total digits are: 4

Explanation:

In the above program, we read an integer number from the user. Then we count the digits of the input number using the recursive function CountDigits(). 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 find the sum of the digits of a gi... >>
<< Ruby program to calculate the power of a given num...