Beginner ยท digit peeling

Digit Sum

Sum the digits of an integer: 1234 โ†’ 1+2+3+4 = 10. Same peel loop as Count the Digits, but accumulating this time.

Problem

Input: one integer n (โˆ’10โน โ‰ค n โ‰ค 10โน).

Output: the sum of its digits (the minus sign doesn't count).

Sample:

InputOutput
123410
-3058

Your solution

Program.cs โ€” your solution
Custom input for "Run my input"

Judging runs entirely in your browser against hidden tests. Your code is saved locally as you type. Ctrl+Enter judges.

Stuck? Hints

Hint 1 โ€” peel and add

Each pass: sum += n % 10; takes the last digit, n = n / 10; drops it. Loop until zero.

Hint 2 โ€” the traps

Negative input loops forever with n > 0 โ€” take Math.Abs(n) first. And n = 0 should print 0 (do-while handles it for free).

Solution (try first!)
int n = Math.Abs(int.Parse(Console.ReadLine()));
int sum = 0;
do { sum += n % 10; n = n / 10; } while (n > 0);
Console.WriteLine(sum);

Same loop, different fold โ€” count became sum. That's the accumulator pattern from Lesson 4 doing its job. Next: Leap Year.