Sum of Digits Program Mathematical Logic
Python Code
num = int(input("Enter a number: "))
s = 0
temp = num
while temp > 0:
digit = temp % 10
s += digit
temp //= 10
print("Sum of digits:", s)
Step-by-Step Explanation
1. Taking User Input:
num = int(input(...)) captures a number from the user as text and converts it into an integer.
2. Initializing Variables:
s = 0 holds the running total sum, while temp = num creates a temporary variable to modify during calculation without altering the original number.
3. The While Loop:
while temp > 0 continuously extracts digits until all numbers are processed.
4. Extracting the Last Digit: Modulus operator
temp % 10 yields the last digit of the number.
5. Accumulating Total:
s += digit adds the newly extracted digit to the running sum.
6. Dropping the Last Digit: Integer division
temp //= 10 removes the processed last digit from temp.
7. Displaying Output:
print(...) presents the cumulative sum of all extracted digits.
Worked Example: Input = 432
Initial State: s = 0, temp = 432
| Iteration | temp % 10 (digit) | s += digit (Sum) | temp //= 10 (Remaining) |
|---|---|---|---|
| 1 | 432 % 10 = 2 | 0 + 2 = 2 | 432 // 10 = 43 |
| 2 | 43 % 10 = 3 | 2 + 3 = 5 | 43 // 10 = 4 |
| 3 | 4 % 10 = 4 | 5 + 4 = 9 | 4 // 10 = 0 (Loop ends) |
Final Output: Sum of digits: 9