Tuesday, May 24, 2011

Add 2 Numbers without using operator

Addition of 2 numbers without using '+' operator:

Algorithm :
(1) Given two numbers X and Y
(2) Check if addend (i.e. X) is 0 or not.
(3) If Addend is 0 (i.e X == 0) then return Y
     Else do the following :
    (3.1) Repeat this algorithm from step (1) by replacing X and Y as follows:
             X = ( X & Y ) << 1 [ Left Shift the result of ( Bitwise and X , Y) by 1]
             Y = ( X ^ Y ) [ Bitwise XOR of X, Y]
       
 Note: If X is a number equal to 2 power 'n', then X & Y will be always 0

C Program:

#include <stdio.h>

int add(int x, int y)
{
        if(!x) return y;
        else
         {
                //printf("\nIn Add N1: %d, N2: %d", x, y);
                return add((x & y) << 1,x ^ y);
         }
}

int main()
{
        int x, y;
        printf("\nEnter X and Y values: ");
        scanf("%d %d",&x,&y);
        printf("\nEntered values are X = %d, Y = %d \n",x,y);
        int z = 0;
        //z = ~x;
        //printf("z is %d", z<<1);
        printf("\nSum is %d\n\n",add(x,y));
        return 0;
}