Monday, December 20, 2010

Addition without using the + operator in C

Write a C function which does the addition of two integers without using the '+' operator. You can use only the bitwise operators.(Remember the good old method of implementing the full-adder circuit using the OR and XOR gates....)


Now, for the code implemented in C.
#include<stdio.h>
int main()
{
    int a = 12, b = 25;
    while (b)
    {
        int carry = a & b;
        a = a ^ b;
        b = carry << 1;
    }
    printf("%d\n",a);
}

Cheers!
Jack

No comments: