How do I add two numbers without using ++ or + or any other arithmetic operator in C/C++?


In this article we will see how to add two numbers without using arithmetic operators like +, ++, -, or --.

To solve this problem, we can solve them using binary adder logic. In that case we were designed half adder and full adder. These adders can add one bit binary numbers. By cascading multiple adders, we have can create circuit to add bigger numbers.

In that adder, we have performed XOR operation among the numbers, then for the carry we were performing the ANDing logic. These features are implemented here to add two numbers.

Example Code

 Live Demo

#include <iostream>
using namespace std;
int add(int a, int b) {
   while (b != 0) {         //until there is no carry, iterater
      int carry = a & b;    //find carry by anding a and b
      a = a ^ b;           //perform XOR on a and b, and store into a
      b = carry << 1;     //the carry is shifted one bit to the left, and store it to b
   }
   return a;
}
int main() {
   int a, b;
   cout << "Enter two numbers to add: ";
   cin >> a >> b;
   cout << "The result is: " << add(a, b);
   return 0;
}

Output

Enter two numbers to add: 56
23
The result is: 79

Updated on: 30-Jul-2019

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements