1

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

3 Answers3

2

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);
}
Itban Saeed
  • 1,660
  • 5
  • 25
  • 38
0

In the begining of your loop set sum to 0. So that before taking sum over next set of elements it is reinitialized to zero.

for(i=0; i<t; i++) 
  { 
    sum = 0;
    scanf("%d", &n);
H S
  • 1,211
  • 6
  • 11
0

You need to set your sum=0; on the first line of the for loop.

Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27