Q:

Ruby program to count the number of digits in a number

0

Ruby does not provide you any predefined direct method through which you can find the number of digits in a number. Though one method can be implemented by converting the number into a string and then apply .length method to it. In that case, the expression will look like “number.to_s.length” but that requires conversion of number into a string. If you do not want to apply such type of method then you can go for the code given below.

Methods used:

  • puts: This method is a predefined method which is used to print a string on the console.
  • gets: The gets method is used to get a string from the user through the console.

Variables used:

  • num: This variable is storing the number which is provided by the user.
  • temp: This is acting as the temporary variable which is storing the value available in num.
  • count: This is acting as a counter variable. It is storing the number of digits available in num.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Ruby code to count the number of digits in a number

=begin
Ruby program to count the number of digits
=end

puts "Enter the number:"
num=gets.chomp.to_i

temp=num
count=0

while (temp>0)
	count+=1
	temp=temp/10
end

puts "#{num} has #{count} digits"

Output

RUN 1:
Enter the number
89744
89744 has 5 digits

RUN 2:
Enter the number
8171627331
8171627331 has 10 digits

Code explanation:

You can observe in the above code that we have taken a variable count, which is behaving as a counter and counting the number of digits. The count is initialized by 0 and is incrementing when the condition mentioned with while loop is coming out to be true. The number is getting divided by 10 after every iteration. The code is not complex and is very easy to understand.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now