AjithAj AjithAj - 6 months ago 26
C Question

Sum of carryover on adding two 4 digit numbers

How to get sum of carryover on adding two 4 digit numbers?

An example would be:

Carryovers 111
First 4 digit 9999
2nd 4 digit 7777
Answer 17776

Here I want to calculate the sum of the carries (answer of summing carries = 3), what should I do?


This is a rather simple task. You may not know it sice you are new here, but SO is not a coding plateform, so you won't get answers unless you show us your code first.

But, since I wanted to try myself on the algorithm, here's a simple answer. I warn you, it won't work on all examples (I won't tell you when this code won't work) and I'm not commenting the code on purpose. I'm smelling the assignment here, so the code is just to give you some pointers, not to make your homework.

Beware: It's just a skeleton and you won't get a good grade if you copy paste it as it is.

int main(int argc, char** argv)
    int numberA = 9999;
    int numberB = 7777;

    int sum_of_carryovers = 0;

    while (numberA > 9 && numberB > 9)
        int digitA = numberA % 10;
        int digitB = numberB % 10;

        int sum = digitA + digitB;

        if (sum > 9)
            sum_of_carryovers += 1;

        numberA /= 10;
        numberB /= 10;

    printf("The sum of carryovers = %d\n", sum_of_carryovers);