This blog is under construction

Sunday 14 July 2013

C program to add two numbers using bitwise operator

Write a C program to add two numbers using bitwise operator.
Please check the below link to get better understanding about this program.


  #include <stdio.h>

  int bitwiseAdd(int input1, int input2) {
        int carry;
        while (input2 != 0) {
                /* calculating the carry and do a left shift*/
                carry = (input1 & input2) << 1;
                /* calculating the sum */
                input1 = input1 ^ input2;
                input2 = carry;
        }
        return input1;
  }

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


        /*
         *  add input1 and input2 and store the 
         *  ouput in result
         */
        result = bitwiseAdd(input1, input2);
        printf("Sum of %d and %d is %d\n", input1, input2, result);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first input:10   
  Enter your second input:33
  Sum of 10 and 33 is 43


No comments:

Post a Comment