Advertisements
Advertisements
Question
Write a program to find the sum of digits of an integer number, input by the user.
Answer in Brief
Advertisements
Solution
The program can be written in two ways.
- The number entered by the user can be converted to an integer and then by using the 'modulus' and 'floor' operators it can be added digit by digit to a variable 'sum'.
- The number is iterated as a string and just before adding it to the 'sum' variable, the character is converted to the integer data type.
Program 1:
#Program to find sum of digits of an integer number
#Initializing the sum to zero
sum = 0
#Getting user input
n = int(input("Enter the number: "))
# looping through each digit of the number
# Modulo by 10 will give the first digit and
# floor operator decreases the digit 1 by 1
while n > 0:
digit = n % 10
sum = sum + digit
n = n//10
# Printing the sum
print("The sum of digits of the number is",sum)
OUTPUT:
Enter the number: 23
The sum of digits of the number is 5
Program 2:
#Initializing the sum to zero
sum = 0
#Asking the user for input and storing it as a string
n = input("Enter the number: ")
#looping through each digit of the string
#Converting it to int and then adding it to the sum
for i in n:
sum = sum + int(i)
# Printing the sum
print("The sum of digits of the number is",sum)
OUTPUT:
Enter the number: 44
The sum of digits of the number is 8.
shaalaa.com
Is there an error in this question or solution?
