Thursday, 16 February 2017

Adding Two Integer Numbers Without Using + Operator in C/C++

Using the concept of boolean algebra we can get sum of two integers without using the plus operator or any other mathematical operator like -,x,/ etc. 

We know that the outputs of half adder is (Sum = A XOR B , Carry = A AND B ) and in the full adder the carry is added to the sum and also in the parallel adder the output carry is shifting in the left side. In C/C++ XOR, AND and Left Shift operations are defined using ^ , &, << operators respectively.

Source code:
#include<stdio.h>
#include<conio.h>
int FullAdder(int x, int y)
{
       int S = (x) ^ (y);          //Output Sum Of Half Adder
       int C = (x)&  (y);        //Output Carry Of Half Adder
       if (y == 0)
       {
              return x;
       }
       else if (x == 0)
       {
              return y;
       }
       else
       {
              return FullAdder(S, C << 1);
       }
}
int main()
{
       printf("Sum of 57863, 78437 = %d\n", FullAdder(57863, 78437));
       printf("Sum of 34567, 23453 = %d\n", FullAdder(34567, 23453));
       printf("Sum of 57863, 78437, 34654 = %d\n", FullAdder(FullAdder(57863, 78437), 34654));
       printf("Sum of 57, 784,4354,64657,344546 = %d\n", FullAdder(FullAdder(FullAdder(57, 784), FullAdder(4354, 64657)), 344546));
       _getch();
       return 0;
}
Output of the code: