Tuesday, May 24, 2011

Sub 2 Numbers without using operator

Subtract 2 Numbers without using '-' operator.

The algorithm for Subtract is same as Algorithm for Addition except we need to pass the values as follows:
Algorithm:
(1) Given two number X and Y
(2) Call Add algorithm by passing arguments as X and 2's complement of Y


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 sub(int x, int y)
{
        //We need to pass 2nd argument as 2's complement of Y
        // i.e. add(~y,1) == 2's complement of Y
        return add(x, add(~y,1));
}

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);
        printf("\nSub : X - Y:  %d - %d = %d\n\n",x, y, sub(x,y));
        return 0;
}


No comments:

Post a Comment