How to sum two integers without using arithmetic operators in C/C++?

CC++Server Side Programming

The following is an example to add two numbers without using arithmetic operators.

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
int add(int val1, int val2) {
   while(val2 != 0) {
      int c = val1 & val2;
      val1 = val1 ^ val2;
      val2 = c << 1;
   }
   return val1;
}
int main() {
   cout <<"The sum of two numbers : "<< add(28, 8);
   return 0;
}

Output

The sum of two numbers : 36

In the above program, a function add() is defined with two int type arguments. The addition of two numbers is coded in add()

int add(int val1, int val2) {
   while(val2 != 0) {
      int c = val1 & val2;
      val1 = val1 ^ val2;
      val2 = c << 1;
   }
   return val1;
}

In the main() function, the result is printed by calling function add()

cout <<"The sum of two numbers : "<< add(28, 8);
raja
Published on 08-Nov-2018 10:37:44
Advertisements