Write a program to add two numbers a and b.
1. Without Using + operator
2. Without using any loops
Sum = A XOR B
Carry = A AND B
#include <iostream>
int add(int p, int q)
{
if(q == 0)
return p;
int k, r;
k = p ^ q;
r = p & q;
return add(k, r<<1); // carry left shift 1 bit
}
int main() {
printf("%d\n", add(4,7));
printf("%d\n", add(401,7));
printf("%d\n", add(14,7));
printf("%d\n", add(4,47));
printf("%d\n", add(4,-97));
printf("%d\n", add(-4,-97));
}
output:
11
408
21
51
-93
-101