melkadri melkadri - 9 days ago 4x
C Question

Adding digits of an integer in C

My program asks the user to input an integer and adds the sum of the digits.

#include <stdio.h>

int main (void)
int inputNum, sum;

// Gets the inputNum
printf("Type in a positive integer, and this program\nwill calculate the sums of the digits: ");
scanf("%i", &inputNum);

sum += (inputNum % 10);
inputNum /= 10;
} while (inputNum != 0);

printf("Your sum is: %i\n", sum);

But every time it put an integer in, I get a number around 36000. I saw another example online that used %d, so I tried it but it made no difference. Am I just going in the wrong direction from the start? Thanks in advance.


You never initialized sum; it may well be starting with value 1,000,000

Just do:

int inputNum, sum = 0;