Addition of numbers without arithmetic operator

Hi friends today i'm going to explain about a program to add numbers without arithmetic operators.

#include< iostream.h >
int add(int a,int b)
{
if(!a)
{
return(b);
}
else
{
return add((a&b) < < 1,(a^b));
}
}
main()
{
int c;
c=add(1,2);
cout < < c;
}

How it works ?

This is one of question asked in interview. This program based on half adder circuit. In half adder , summation is produce result of ex-or of two bits carry produce result of and of two bits. Now the logic in this program is if carry exists, we should do ex-or operation with addition and carry which is shifted 1 position.

in this program
when add function is called a=1 b=2. If(!a) won't true. So else will work. It call add function itself (recursive function) with values add operation of a and b and shifted one position left.add operation is
a= 0001
b= 0010
------------
0000 and this will shifted one position left. Now it's same zero.
and ex-or operation is
a=0001
b=0010
----------
0011
now this two two values passed to add function. Now if(!a) work. Because not of 0's will 1's so it'll return b as sum of a and b.

Related Posts