Write a program in python to find the sum of digits of a number.
Input: 1234 Output: 10 Input: 101 Output: 2
To add digits, we need to extract each digit one by one as a remainder using the modulo of 10 (
num%10) and add it to the sum.
Since we are extracting the last digit from the number, so we need to remove the last digit after we have successfully added it to the sum so that the next digit can be extracted.
Hence to remove the last digit we need to update the number with
num/10 because the quotient does not contain the last digit when the divisor is 10.
These steps need to be repeated for all the digits of the number.
Let’s see the source code.
num = int(input("Input a number: ")) #Initialize sum with 0 sum =0 #Loop through the digits until the number reduces to 0 while num>0: sum += num%10 num = num//10 print("Sum of the digits: ",sum)
Input a number: 1234 Sum of the digits: 10
Python Program to Find the Sum of Digits using Function
In this method, the overall algorithm of the program is same as the above program. The only difference is that we need to write the main logic inside a function and return the sum result at the end.
def sumOfDigits(num): #Initialize sum with 0 sum =0 while num>0: sum += num%10 num = num//10 return sum num = int(input("Input a number: ")) print("Sum of the digits: ",sumOfDigits(num))
Input a number: 1111 Sum of the digits: 5
To add digits we can also use recursion but it is not recommended. If you still want the recursion code to add digits in python then please comment below.
This Post Has One Comment
How came 5, it’s a 4