Programming Exercises · Q7
Q.Write a program to find the sum of digits of an integer number, input by the user.
Punjab PsebTextbookSubjective· 3mImportance★★★★★est
92% · 36/39 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Extract the last digit with n % 10, drop it with n // 10, and accumulate until n becomes 0 — the classic digit-manipulation while loop.
The idea. The modulo and integer-division operators are a natural digit toolkit: n % 10 yields the last digit, and n // 10 gives the number without that digit. Repeating the pair until the number is exhausted visits every digit exactly once — and since we cannot know beforehand how many digits the user's number has, an indefinite while loop (not a counted for) is the right construct.
Algorithm
- Input the number; take its absolute value (so a negative input still works).
- Set digit_sum = 0.
- While n > 0: add n % 10 to digit_sum; set n = n // 10.
- Print digit_sum.
Program
num = int(input("Enter a number: "))
n = abs(num)
digit_sum = 0
while n > 0:
digit_sum += n % 10
n = n // 10
print("Sum of digits:", digit_sum)
Sample run
Enter a number: 6789
Sum of digits: 30
Trace for 6789
| n at start of pass | n % 10 | digit_sum | n // 10 |
|---|---|---|---|
| 6789 | 9 | 9 | 678 |
| 678 | 8 | 17 | 67 |
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.