简体   繁体   中英

Find the sum of digits of a number(in c)

I need to find the sum of the digits of a number. For example, the sum of the digits of the number 1123 is 1+1+2+3 =7

My idea:

1)User enters and integer

2)I calculate the number of digits in the number(in case above - 4 digits)

3)Than using for loop I divide users number by 10 to the power of 1,2...till the number of digits(not including the last one) and sum the numbers.

Here is my code:

int main (void)
{
    int result,sum,n;
    int div = 10,counter = 0,number;

    printf("Enter the integer:");
    scanf("%i",&number);
    while(result >0){
        result = number/div;
        div *= 10;
        ++counter;
    }
    printf("The number consists of %i digits\n",counter);
    sum = 0;

    for(n=1;n<counter;++n){
        sum += number/pow(10,n);
    }
    printf("%i",sum);

    return 0;


}

the first part(while loop) separately works correct. But together with second part(for loop) it gives me incorrect result(0 digits from the while loop and the sum is also zero). Can you explain why does it happen? How can I correct my solution?

PS I know that exist more efficient solutions of my problem, but i want to use my own algorithm.

Several problems here:

  • When you first enter the while loop, result has not been initialized. Attempting to read an uninitialized variable is undefined behavior .
  • When you do the division, you aren't adding digits. You're adding the number divided by successive powers of 10. In the case of 1123, you're actually adding 112 + 11 + 1. You need to use modulus instead of division to get the digits.

You can do the adding and counting of digits in a single loop as follows:

sum = 0;
while(number > 0){
    sum += number % 10;
    number /= 10;
    ++counter;
}
printf("The number consists of %i digits\n",counter);
printf("%i",sum);

much simpler:

result = number;
sum = 0;
counter = 0;
while(result != 0){
    sum += result % 10;
    result /= 10;
    ++counter;
}

printf ("Counter:%d sum:%d\n", counter, sum);

First of all, for best debugging, use a number which has different digits, like 12345.

To do debugging, calculate and print the digit separately from accumulating it. That is, instead of sum += <... complex code ...> , do it like this:

int digit = ...
printf("Next digit is %i\n", digit);
sum += digit;

Also (you should discover this by debugging, but it's obvious enough to note directly), your algorithm for calculation of digits is wrong. Do something like this:

int div = 1;
for (...)
{
    digit = number / div % 10;
    div *= 10;
}

Note that I don't use pow here, because pow uses floating-point arithmetic, which has limited accuracy. If your int has 64 bits of precision (unlikely but possible), floating-point will calculate nonsense for large numbers (it has only 53 bits of precision).

There are many errors in the code, but overall the whole approach is wrong. Counting the digits is unnecessary.

A simpler way would be:

unsigned temp = number, sum = 0;
while (temp) {
  sum += temp % 10;
  temp /= 10;
}

Notice that you know when to stop looping because temp becomes 0 ( temp as a condition is equivalent to temp != 0 ). You don't need to know the number of digits in advance.

If going with your code, this'll work:

for(n=1;n<=counter;++n){
    sum += number%10;
    number /= 10;
}
printf("%d",sum);

Simpler solution:

int c, n=0, sum=0;
printf("Enter number");
while((c=getchar())!='\n') {    // IMPORTANT: '\n' in unix, '\r' in windows
    if(c<'0' || c>'9') {
        printf("Bad value");
        break;
    }
    sum+=c-'0';    // c is the ASCII code of the digit, so you have to subtract an offset
    n++;
}
printf("Number of digits: %d", n);
printf("Sum of digits: %d", sum;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM