vendredi 24 juillet 2020

Add digits together and when >9 add digits together again

The problem I have is: I want that, when sum1 > 9 (in this example (2 * 6) + (2 * 6) = 24), then, instead of taking 12+12,I would like to add the given digits together (1+2+1+2=6), which becomes sum11. I don't know, how I can nest this together. I tried something with while(sum1>9), but it didn‘t worked. My code looks like this:

int main(void)
{
    long n=6666, m,r,i,sum1,sum2,sum11=0;
    sum1=0; sum2=0;

    for (m=n,i=1;m!=0;m=m/10,i++)
    { 
        r=m%10;

        if(i%2!=0)
        sum1+=r*2;

        else
        sum2+=r;
        
    }
    printf("\nSum1=%ld Sum2=%ld", sum1,sum2);
    printf("\nSum11=%ld\n", sum11);
}

If I now enter the number 6666, I get the following Output:

Sum1=24 Sum2=12
Sum11=0

How can I change the code, that sum11 displays 6 (1+2+1+2) from sum1 (2 * 6 + 2 * 6).

Aucun commentaire:

Enregistrer un commentaire