Add two numbers without using Arithmetic Operators in C++
In this tutorial, we will learn how to add two numbers without using any arithmetic operators along with its implementation in C++.
Add two numbers without using Arithmetic Operators
We wish to add two numbers without using any arithmetic operators like +, -, *, / etc. One way of doing this is by using bitwise operators.
If we have two single-bit binary numbers then we can find their sum by simple half adder logic. That is we get the sum by performing bitwise XOR(exclusive-OR) operation and the carry by performing bitwise AND operation. We can extend this logic to perform the addition of any length binary numbers.
Example:
First binary number = 1 First binary number = 1
Second binary number = 0 Second binary number = 0
——————————————– ——————————————–
Carry (AND) = 0 Sum (XOR) = 1
——————————————– ——————————————–
Implementation in C++
#include <iostream> using namespace std; int main() { int num_1, num_2; cout << "Enter two numbers "; cin >> num_1 >> num_2; int carry; while (num_2 != 0) { carry = num_1 & num_2; num_1 = num_1 ^ num_2; num_2 = carry << 1; } cout << "Sum is " << num_1; return 0; }
Consider two numbers 12 and 4 as input and let us see how the code is working.
12 in binary = 1100
4 in binary = 0100
num_1 = 1100 num_1 = 1100
num_2 = 0100 num_2 = 0100 carry = 0100
—————————– —————————– ——————————
carry(AND) = 0100 num_1(XOR) = 1000 num_2(<<1) = 1000
—————————– —————————– ——————————
num_1 = 1000 num_1 = 1000
num_2 = 1000 num_2 = 1000 carry = 01000
—————————– —————————– ——————————
carry(AND) = 1000 num_1(XOR) = 0000 num_2(<<1) = 10000
—————————– —————————– ——————————
num_1 = 00000 num_1 = 00000
num_2 = 10000 num_2 = 10000 carry = 00000
—————————– ——————————— ——————————
carry(AND) = 00000 num_1(XOR) = 10000 num_2(<<1) = 000000
—————————– ——————————— ——————————
Now, num_2 became zero and we come out of the while loop. And, num_1 = 10000 whose decimal equivalent is 16 i.e., the sum of 12 and 4. In this way, we obtain the sum of two numbers without using any arithmetic operators in C++.
Output:
Enter two numbers 12 4 Sum is 16
Also read, Print prime numbers in C++
Height of a binary tree in C++
Leave a Reply