C++ Program to calculate sum of two numbers without using arithmetic operator [DEVCPP/GCC]

EXPLANATION

Let the two numbers a and b be 3 and 2. These numbers are represented in binary as:

3 = 011
2 = 010

ITERATION 1

I. Calculate carry (carry = a & b)

a:   0 1 1
b:   0 1 0
     _____
      0 1 0 

II. Calculate sum (a = a ^ b) (XOR operation)

a:   0 1 1
b:   0 1 0
      _____
       0 0 1

III. Update the value of b (b = carry << 1)

b  =  carry << 1
b  =  0 1 0 << 1
b  =  1 0 0

ITERATION 2

I. Calculate carry (carry = a & b)

a:   0 0 1
b:   1 0 0
     _____
      0 0 0

II. Calculate sum (a = a ^ b)

a:   0 0 1
b:   1 0 0
     _____
      1 0 1

III. Update the value of b (b = carry << 1)

b  =  carry << 1
b  =  0 0 0 << 1
b  =  0 0 0

Since, b has become 0, the calculation stops and leads us with sum as 1 0 1(5).

PROGRAM

// Program to calculate sum of two numbers without using arithmetic operator

#include <iostream>

using namespace std;

int main()
{
        int a,b,carry;

        cout<<"ENTER A: ";
        cin>>a;

        cout<<"ENTER B: ";
        cin>>b;

        while (b != 0)
        {
              carry = (a & b) ;
              a = a^b;
              b = carry << 1;
        }
     
        cout<<"SUM : "<<a;
 
        return 0;
}

OUTPUT


C++ Program to calculate sum of two numbers without using arithmetic operator with output



Share this

Related Posts

FIND US ON FACEBOOK!