C++ Program to Perform Addition Operation Using Bitwise Operators

«
»
This is a C++ Program to perform addition using bitwise operators. Using AND and XOR operators addition can be done, where carry is given by AND between two operands and result can be given by XOR between two operands.

Here is source code of the C++ Program to Perform Addition Operation Using Bitwise Operators. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include<iostream>
  2. #include<conio.h>
  3. #include<stdlib.h>
  4.  
  5. using namespace std;
  6. int add(int x, int y)
  7. {
  8.     int carry;
  9.     while (y != 0)
  10.     {
  11.         carry = x & y;
  12.         x = x ^ y;
  13.         y = carry << 1;
  14.     }
  15.     return x;
  16. }
  17. int main(int argc, char **argv)
  18. {
  19.  
  20.     cout << "Enter the numbers to be added:";
  21.     int x, y;
  22.     cin >> x >> y;
  23.     cout << "The Summation is: " << add(x, y);
  24. }

Output:

advertisement
$ g++ BitWiseAddition.cpp
$ a.out
 
Enter the numbers to be added:23 24
The Summation is: 47

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement

Here’s the list of Best Books in C++ Programming, Data Structures and Algorithms.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.