Beginner · digits

Sum of Digits

Read a positive integer and print the sum of its digits: 12345 → 1+2+3+4+5 = 15. Third appearance of the digit-chopping pattern — by now it should feel familiar.

At a glanceAdd the digits with sum += n % 10 and n /= 10 until n is 0 — the chopping pattern that turns any digit problem into a loop.

Problem

Input: one positive integer N (1 ≤ N ≤ 10⁹).

Output: the sum of the digits of N.

Samples:

InputOutput
1234515
10001

Your solution

main.cpp — your solution
Custom input for "Run my input"

Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.

Stuck? Hints

Hint 1 — the pattern, once more

n % 10 pops the last digit, n / 10 removes it. In Count the Digits you counted pops; in Reverse a Number you pushed them back. Here you just add each popped digit into an accumulator.

Hint 2 — the loop end

while (n > 0) — every positive number eventually reaches 0 after enough divisions by 10. When it does, the accumulator holds the answer.

Solution (try it first!)
#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int s = 0;
    while (n > 0) {
        s += n % 10;
        n /= 10;
    }
    cout << s << endl;
    return 0;
}

You now own the whole digit-toolkit: count, reverse, sum. A good remix: digit product, or "does digit 7 appear?" (an if inside the loop). Related reading: integer division.

Deep dive

Why this works

Same peel, different accumulator. Recognising that a new problem is an old loop with a new body is the skill this whole practice section trains.

The cost

O(d), d ≤ 10 for int. The loop count depends on the number of digits, not the magnitude.

Where it goes wrong

  • Forgetting the division (n % 10 forever) gives an infinite loop that freezes the tab.
  • -123 % 10 is -3 in C++, so the sum of a negative number comes out negative. Take abs first.

Next step

Store the peeled digits and reverse them: Reverse a Number.

Two things to remember

  • Modulo of a negative is negative in C++ — abs() first.
  • New problem, old loop: only the body changes.
🐞 This version fails — open it and try

Types / where % was needed

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int sum = 0;
    while (n > 0) {
        sum += n / 10;
        n /= 10;
    }
    cout << sum << endl;
    return 0;
}