Ruby program to sum of digits of a number



Write a Ruby program to sum of digits of a number

class SumNumberDigits
  def getSumOfDigits
    sum = 0 
    rem = 0 
    print "Enter the number: "
    num = gets.chomp.to_i 
    while num !=0 do
      rem = num % 10 
      num = num / 10 
      sum += rem 
    end
    print "Sum of digits of number is :" + sum.to_s
  end
end

p = SumNumberDigits.new 
p.getSumOfDigits

Output:


Enter the number:  12345
Sum of digits of number is :15


No comments:

Post a Comment