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


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);

Updated on: 26-Jun-2020

171 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements