DavidHaGever
DavidHaGever

Reputation: 9

how do I add up the sum of the digits of a number except for digits that repeat themselves in c?

I have an assignment and I need to add up the digits of it and ignore the once that repeat themselves for example 234111 -> 2 + 3 + 4 + 1 -> 10 I tried doing this: #include

int main(void)
{
int i = 0;
int num = 0;
int sum = 0;

printf("Please enter a number\n");
scanf("%d", &num);

while(num > 0){

    sum += num%10;
    num /= 10;

}
printf("%d", sum);
return 0;
}

what I did just adds up the digits, it doesn't ignore that ones that get repeated What do i need to add to the code?

Upvotes: 1

Views: 208

Answers (2)

William Pursell
William Pursell

Reputation: 212634

Just read each character and record if you've already seen it:

#include <stdio.h>
#include <ctype.h>

int
main(void)
{
        int seen[10] = {0};
        int sum = 0;
        int c;
        while( ( c = getchar()) != EOF ) {
                int v = c - '0';
                if( isspace(c)) {
                        continue;
                }
                if( v < 0 || v > 9 ) {
                        fprintf(stderr, "Invalid input\n");
                        return 1;
                }
                if( ! seen[v]++ )
                        sum += v;
        }
        printf("%d\n", sum);
        return 0;
}

Upvotes: 0

Adrian Mole
Adrian Mole

Reputation: 51894

You can keep an array of 'flags' for which digits have been used already:

#include <stdio.h>

int main(void)
{
//  int i = 0; // You don't actually use this in the code!
    int num = 0;
    int sum = 0;
    int used[10] = { 0, }; // Set all "used" flags to zero

    printf("Please enter a number\n");
    scanf("%d", &num);

    while (num > 0)
    {
        int digit = num % 10; // Get the digit
        if (!used[digit]) sum += digit; // Only add if not used already
        used[digit] = 1; // Now we have used it!
        num /= 10;

    }
    printf("%d", sum);
    return 0;
}

Feel free to ask for further clarification and/or explanation.

Upvotes: 2

Related Questions