This blog is under construction

Sunday 7 July 2013

C program to add two numbers without using addition operator

How to add two numbers without using arithmetic(addition) operator?
We can use half adder logic to add two integers.

For example, x and y are the two integers whose values are 3 and 7 correspondingly.
x = 3, y = 7
a ^ b  => X-OR operation between two bits gives sum value
a & b => AND operation between two bits gives carry.

We are going to use the above logic to perform addition of two integers x and y.
00000011 is the binary value for 3
00000111 is the binary value for 7

Find bit-wise X-OR between 3 and 7 to get the sum value.
(00000011 ^ 00000111) => (00000100)
Store the sum in x.  Now, x is 4(00000100).

Find bit-wise AND operation between 3 and 7 to get the carry.
(00000011 & 00000111) => (00000011)
Shift carry by one bit left and store the result in y.  Now, y is 3(00000110).

Proceed the above step until y becomes 0.

Find bit-wise X-OR between x and y to get the sum value.
x = 4, y = 6
(00000100 ^ 00000110) = (00000010)
Store the sum in x.  Now, x is 2

Find bit-wise AND operation between 4 and 6(x and y) to get the carry.
x = 4, y = 6
(00000100 & 00000110) = (00000100)
Shift carry by one bit left and store the result in y.  Now, y is 8(00001000)

Again, we need to find sum and carry since the value of y is not 0.

Find bit-wise X-OR between x and y to get the sum value.
x = 2, y = 8
(00000010 ^ 00001000) = (00001010)
Store the sum in x.  Now, x is 10

Find bit-wise AND operation between 2 and 8(x and y) to get the carry.
x = 2, y = 8
(00000010 & 00001000) = (00000000)
Shift carry by one bit left and store the result in y.  The value of y is 0.  So, we found the output and the sum of 3 and 7 is 10(x is 10).

Write a C program to add two numbers without using arithmetic operator.


  #include <stdio.h>

  /* adds two number without addition operator */
  int addTwoNum(int a, int b) {
        int carry;
        while (b != 0) {
                /* calculating the carry and do a left shift*/
                carry = (a & b) << 1;
                /* calculating the sum */
                a = a ^ b;
                b = carry;
        }
        return a;
  }

  int main () {
        int a, b, res;
        /* get the input from the user */
        printf ("Enter your first input:");
        scanf("%d", &a);
        printf("Enter your second input:");
        scanf("%d", &b);

        /* adds two number without using arimetic operator */
        res = addTwoNum(a, b);
        printf("Sum of %d and %d is %d\n", a, b, res);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input:99
  Enter your second input:199
  Sum of 99 and 199 is 298



No comments:

Post a Comment