Skip to study material
← Question index

QUESTION 38 · Loop Applications

Write a C program to find the sum of digits of a non-negative integer.

5 marks

Answer in brief

The sum of digits is obtained by extracting each decimal digit and adding it to a running total.

Algorithm

  1. Read a non-negative integer n.
  2. Set sum to 0 and copy n to remaining.
  3. While remaining > 0, add remaining % 10 to sum and divide remaining by 10.
  4. Print sum.

Worked trace

For n = 472, the first digit is 2, sum becomes 2 and remaining becomes 47. Next, digit 7 makes sum equal to 9 and remaining becomes 4. Finally, digit 4 makes sum equal to 13 and remaining becomes 0. The condition is false, so the answer is 13.

Why keep a copy?

Dividing remaining changes it on each iteration. Keeping the original n allows it to be used later if required. The computation itself needs only the current remaining value and the sum.

Boundary cases

For input zero, the while body is skipped and sum stays zero, which is the correct sum of the digits of 0. The example rejects negative input to avoid extra sign-handling rules. It accepts values through 1000000000; the input token must fit long long.

Time and space complexity

If the number has d decimal digits, one digit is removed per iteration. The loop therefore performs d iterations for a positive number: O(d) time. Since the number of digits grows logarithmically with n, this can also be written O(log n) for n > 0. Only a fixed number of integer variables is stored, so auxiliary space is O(1).

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    long long n, remaining;
    int sum = 0;
    if (scanf("%lld", &n) != 1 || n < 0 || n > 1000000000LL) {
        puts("Unsupported input"); return 1;
    }
    remaining = n;
    while (remaining > 0) {
        sum += (int)(remaining % 10);
        remaining /= 10;
    }
    printf("Digit sum = %d\n", sum);
    return 0;
}

Sample input and output

Input

472

Output

Digit sum = 13

Related exam questions

Related questions in the loops category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q6(b) · 8 marks

    How is an entry-controlled loop different from an exit-controlled loop? Explain.

    Paper P01 · page 1
  • March/April 2023 · Q2(b) · 5 marks

    Devise an algorithm for the sum of n numbers using while and for loops.

    Paper P02 · page 1

View this category in the exam question bank →