CameraIcon
CameraIcon
SearchIcon
MyQuestionIcon
MyQuestionIcon
1
You visited us 1 times! Enjoying our articles? Unlock Full Access!
Question

Write a program to find the sum of digits of an integer number, input by the user.

Open in App
Solution

The program can be written in two ways.
1. The number entered by the user can be converted to an integer and then by using 'modulus' and 'floor' operator it can be added digit by digit to a variable 'sum'.
2. The number is iterated as a string and just before adding it to '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 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

flag
Suggest Corrections
thumbs-up
18
Join BYJU'S Learning Program
similar_icon
Related Videos
thumbnail
lock
Arithmetic Progression
MATHEMATICS
Watch in App
Join BYJU'S Learning Program
CrossIcon