When it is required to find the sum of digits in a number without using the method of recursion, the ‘%’ operator, the ‘+’ operator and the ‘//’ operator can be used.
Below is a demonstration for the same −
Example
def sum_of_digits(my_num): sum_val = 0 while (my_num != 0): sum_val = sum_val + (my_num % 10) my_num = my_num//10 return sum_val my_num = 12345671 print("The number is : ") print(my_num) print("The method to calculate sum of digits is being called...") print("The sum of " +str(my_num) + " is : ") print(sum_of_digits(my_num))
Output
The number is : 12345671 The method to calculate sum of digits is being called... The sum of 12345671 is : 29
Explanation
- A method named ‘sum_of_digits’ is defined, that takes a number as parameter.
- A sum is initially assigned to 0.
- The number is divided by 10 and the remainder obtained is added to the sum.
- The number is again floor divided by 10 and assigned to the number itself.
- The sum value is returned as output from the function.
- A number is defined, and is displayed on the console.
- The method is called by passing this number as a parameter.
- The output id displayed on the console.