Skip to content
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
🔒 Locked · start free trial →

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

  1. Input the number; take its absolute value (so a negative input still works).
  2. Set digit_sum = 0.
  3. While n > 0: add n % 10 to digit_sum; set n = n // 10.
  4. 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 passn % 10digit_sumn // 10
678999678
67881767

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.