Alona Chaika
Alona Chaika

Reputation: 3

To get a sum of every second digit, starting from the next to last in C

Im very new in the coding world, so maybe my suggestion to this function is not the best. But how I see it it should work, but it obviously doesn't. What do I do wrong?

//to do checksum
int sum = 0;
for (int i = 2; i <= d; i++ )
{
sum = sum + ((int) (number / pow (10, i - 1)) % 10) * 2;
number = number / 10;

}

printf("%i", sum );

Upvotes: 0

Views: 220

Answers (1)

Shlomi Agiv
Shlomi Agiv

Reputation: 1198

#include <stdio.h>

int main()
{
    int sum = 0;
    int num = 4532199;
    while (num) {
        num /= 10;
        sum += num % 10;
        num /= 10;
    }
    printf("sum=%d\n", sum);
}

Upvotes: 1

Related Questions