ADVERTISEMENT
ADVERTISEMENT

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

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

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.

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.