Search This Blog

Translate This Page

Tuesday, 26 February 2013

Add two numbers without using arithmetic operators

Add two numbers without using arithmetic operators:


Method 1:

#include<stdio.h>
int Add(int x, int y)
{
    // Iterate till there is no carry  
    while (y != 0)
    {
        // carry now contains common set bits of x and y
        int carry = x & y;  

        // Sum of bits of x and y where at least one of the bits is not set
        x = x ^ y; 

        // Carry is shifted by one so that adding it to x gives the required sum
        y = carry << 1;
    }
    return x;
}

int main()
{
    printf("%d", Add(15, 32));
    return 0;
}


Method 2:  (Using for Loop)



int sum(int num1, int num2)
{
    int total, temp, temptotal;  
    total = num1 ^ num2;    
  
    for(temp = num1 & num2; temp != 0;temp = temptotal & temp) 
      {      
      temptotal = total;    
      total = total ^ (temp = temp << 1);  
      }
  
   return total;
}


No comments:

Post a Comment

Latest Current Visitor

World Clock Time, for View Click on Country