return (mul*temp) + sum(a/10, b/10);
Should be:
return temp + 10*sum(a/10, b/10);
You don't need a static variable, Static variables are used to implement a global state whose lifetime extent the entire process. That's not something desirable and should only be used at last resort. Furthermore, that's definitely not what you need here, using static variables to implement your solution will leads to functions that only work the first time they are called.
You should use the recursive property of your algorithm to aggregate the result:
int sum(int a, int b)
{
if(a == 0 && b == 0) {
return 0;
}
else
{
return (a%10) + (b%10) + 10*sum(a/10, b/10);
}
}
sum(1941, 2282)
will expand to :
sum(1941, 2282)
1 + 2 + 10*sum(194, 228)
1 + 2 + 10*(4 + 8 + 10*sum(19, 22))
1 + 2 + 10*(4 + 8 + 10*(9 + 2 + 10*sum(1, 2))
1 + 2 + 10*(4 + 8 + 10*(9 + 2 + 10*(1 + 2 + 10*sum(0, 0))
1 + 2 + 10*(4 + 8 + 10*(9 + 2 + 10*(1 + 2 + 10*0)
You should use the same approach for carry
:
int carry(int a, int b)
{
if(a == 0 && b == 0) {
return 0;
}
else if((a%10) + (b%10) > 9) {
return 1 + carry(a/10, b/10);
}
else {
return carry(a/10, b/10);
}
}
carry(1941, 2282)
will expand to :
carry(1941, 2282)
0 + carry(194, 228)
0 + 1 + carry(19, 22)
0 + 1 + 1 + carry(1, 2)
0 + 1 + 1 + 0 + carry(0, 0)
0 + 1 + 1 + 0 + 0