Search code examples
csum-of-digits

Sum of digits with test cases in C


I am trying to find the sum of digits with test cases. But the problem is after I find one sum, this sum is adding to the next sum but I only one particular sum of that numbers' digit. Please help. Here is my code:


#include <stdio.h>

int main() {
    int t, n, i, r, sum=0;
    scanf("%d", &t);

    for(i=0; i<t; i++) {
        scanf("%d", &n);
        while(n>0) {
            r = n % 10;
            sum = sum + r;
            n = n / 10;
        }
        printf("%d\n", sum);
    }

    return 0;
}


And Here is my output:

3
1234
10
2347
26
8744
49

Why my previous sum adding to the next sum? I am not understanding.

My desired output:

3
1234
10
2347
16
8744
23


Solution

  • Problem:

    Your variable sum is set to 0 on the start of the program and you are adding the sum of each test case in the same variable without cleaning the result of the previous test case (by setting sum = 0 before the next test case starts.)

    Possible Solution:

    Initialize your your variable sum before a test case starts.

    Code:

    for(i=0; i<t; i++)
    {
        scanf("%d", &n);
    
        sum = 0; //Set sum = 0
    
        //Test Case started in while loop
        while(n>0) {
            r = n % 10;
            sum = sum + r;
            n = n / 10;
        }
        printf("%d\n", sum);
    }