C++ Program to Perform Addition Operation Using Bitwise Operators

C++ProgrammingServer Side Programming

Bitwise operators are used to perform bitwise operations. That implies the manipulation of bits. Some of the bitwise operators are bitwise AND, bitwise OR, bitwise XOR etc.

A program to perform addition operation using bitwise operators is given below −

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   int num1, num2, carry;
   cout << "Enter first number:"<<endl;
   cin >> num1;
   cout << "Enter second number:"<<endl;
   cin >> num2;

   while (num2 != 0) {
      carry = num1 & num2;
      num1 = num1 ^ num2;
      num2 = carry << 1;
   }
   cout << "The Sum is: " << num1;
   return 0;
}

Output

The output of the above program is as follows −

Enter first number:11
Enter second number: 5
The Sum is: 16

In the above program, the two numbers are obtained from the user. This is given below −

cout << "Enter first number:"<<endl;
cin >> num1;

cout << "Enter second number:"<<endl;
cin >> num2;

After that, addition is carried out using a while loop. It involves using the bitwise AND, bitwise XOR and left shift operators. The code snippet is given below −

while (num2 != 0) {
   carry = num1 & num2;
   num1 = num1 ^ num2;
   num2 = carry << 1;
}

Finally, the sum is displayed. This is given below −

cout << "The Sum is: " << num1;
raja
Published on 23-Oct-2018 11:30:26
Advertisements