Write a program in python to find the sum of digits of a number.

Example:

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.

Output

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.

Output

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.

Leave a Reply