Jason - 1 year ago 55

C Question

I'm doing an assignment which requires me to add 2 int and requires me to do recursion. Below is my code but my output is always 10 more then the answer. Why? My initial carry is 0.

`int add(int n1,int n2,int carry){`

if(n1>0){

if(carry == 1)

n1= n1+1;

if((n1%10+n2%10)>9)

return n1%10 + n2%10 + 10*add(n1/10,n2/10,1);

else

return n1%10 + n2%10 + 10*add(n1/10,n2/10,0);

}

else{

return 0;

}

}

Answer Source

It is evident if you follow *by hand* your program. Let's follow add(8, 7, 0):

- carry is 0: nothing to do
- n1%10+n2%10 = 15 > 9: ok we will have a carry return 8 + 7 + 10 * add(0, 0, 1) !

The error is here: you get 25 instead of 15 because you correctly add the carry but fail to use only the mod of the sum: it should be ((8 + 7) % 10) + 10 * add(0, 0, 1)

So your code should become:

```
...
if((n1%10+n2%10)>9) {
return ((n1%10 + n2%10) % 10) + 10*add(n1/10,n2/10,1);
}
else {
...
```

But this code only makes sense for academic purposes. It would be terrible in real world code because you simulate 10 based operation on a 32bits (or more) processor...