C++ Program to Add Two Binary Numbers

In this article, you'll learn and get code on the addition of two binary numbers entered by user at run-time. Here I've created programs of binary number addition in following ways:

  • Add binary numbers using string data type
  • Add binary numbers using int (and long int) data type
  • Add binary numbers using user-defined function

Note - If you don't know the basic rules of binary number addition, you can refer to its separate tutorial.

Add Binary Numbers using string Data Type

The question is, write a program in C++, that receives two binary numbers as input to find and print its addition. The program given below uses string data type to do the task. The size() function returns the length of string.

#include<iostream>
using namespace std;

int main()
{
   string bin1, bin2, addRes;
   int len, carry, re, i;
   cout<<"Enter First Binary Number: ";
   cin>>bin1;
   cout<<"Enter Second Binary Number: ";
   cin>>bin2;
   len = bin1.size();
   addRes = "";
   carry = 0;
   for(i=(len-1); i>-1; i--)
   {
      re = carry;
      if(bin1[i] == '1')
         re = re+1;
      else
         re = re+0;
      if(bin2[i] == '1')
         re = re+1;
      else
         re = re+0;
      if(re%2==1)
         addRes = '1' + addRes;
      else
         addRes = '0' + addRes;
      if(re<2)
         carry = 0;
      else
         carry = 1;
   }
   if(carry!=0)
      addRes = '1' + addRes;
   cout<<"\nAddition Result = "<<addRes;
   return 0;
}

Here is the initial output produced by above C++ program:

c++ add two binary numbers

Now supply inputs say 11101 as first and 11111 as second binary number. Here is its sample run with these user inputs:

binary number addition in c++

The dry run of above program with same user input, that is 11101 and 11111 as two binary numbers goes like:

  • When user enters these two binary inputs, it gets stored in bin1 and bin2 variables respectively. That is of string type. Here is the character-by-character storage of bin1 = "11101" and bin2 = "11111":
    • bin1[0] = '1'
    • bin1[1] = '1'
    • bin1[2] = '1'
    • bin1[3] = '0'
    • bin1[4] = '1'
    • In similar way, all characters gets stored at its respective indexes for second input in bin2
  • Now using the statement
    len = bin1.size();
    the length of first binary number gets initialized to len. Therefore len=5, because there are 5 characters available in bin1
  • The empty string, that is "" and an empty integer, that is 0 gets initialized to two variables, addRes and carry respectively
  • Now the execution of for loop begins, starting with i's value from len-1 or 5-1 or 4
  • Since the condition i>-1 or 4>-1 evaluates to be True, therefore program flow goes inside the loop and evaluates all the statement(s) available inside its body
  • That is, the first statement
    re = carry;
    gets executed. Therefore re=0
  • Now the condition (of first if), bin1[i] == '1' or bin[4] == '1' or '1' == '1' evaluates to be True, therefore re+1 or 0+1 or 1 gets initialized to re
  • Again the condition (of second if), bin2[i] == '1' or bin2[4] == '1' or '1' == '1' evaluates to be True, therefore re+1 or 1+1 or 2 gets initialized to re
  • Again the condition (of third if), re%2==1 or 2%2==1 evaluates to be False, therefore program flow goes to its counter part, that is else and '0' + addRes or '0' + "" or '0' gets initialized to addRes
  • Again the condition (of fourth and last if), re<2 or 2<2 evaluates to be False, therefore program flow goes to else's body and 1 gets initialized to carry. So carry = 1
  • Since all the statement gets executed, therefore program flow goes to the increment part of the loop and the value of i gets decremented. Now i=3
  • Then the condition i>-1 or 3>-1 again evaluates to be True, therefore program flow again goes inside the loop. This process continues, until the condition evaluates to be False
  • After exiting from the loop, or when the condition (i>-1) evaluates to be false, '1' gets added before the addRes variable, only if carry does not equals to 0
  • In this way, the addition of two binary numbers gets calculated

Note - The above program has a limitation. The limitation is that, if the length of two entered binary input is not same or equal, the program doesn't works in correct way. Therefore, here is another program created, that works in all the condition, whether the length of binary number inputs is equal or not.

#include<iostream>
using namespace std;

int main()
{
   string str1, str2, sum="";
   int len1, len2, i, j, ds=0;
   cout<<"Enter the First Binary Number: ";
   cin>>str1;
   cout<<"Enter the Second Binary Number: ";
   cin>>str2;
   len1 = str1.size();
   len2 = str2.size();
   i = len1 - 1;
   j = len2 - 1;
   while(i>=0 || j>=0 || ds==1)
   {
      ds = ds + ((i >= 0) ? str1[i] - '0' : 0);
      ds = ds + ((j >= 0) ? str2[j] - '0' : 0);
      sum = char(ds % 2 + '0') + sum;
      ds = ds/2;
      i--;
      j--;
   }
   cout<<"\nSum = "<<sum;
   return 0;
}

Here is its sample run with user inputs 10110 and 110 as two binary numbers:

add two binary numbers in c++

Binary Number Addition using int Data Type

This is the program, you need I think. Because this program does not uses any string type to do the task. This program is created with all its variables as int type. But the output of both the program is same.

#include<iostream>
using namespace std;

int main()
{
   long int bin_one, bin_two, t1, t2;
   int i=0, rem=0, sum[16];
   cout<<"Enter First Binary Number: ";
   cin>>bin_one;
   cout<<"Enter Second Binary Number: ";
   cin>>bin_two;

   t1 = bin_one;
   t2 = bin_two;

   while(bin_one !=0 || bin_two !=0)
   {
      sum[i++] = (bin_one % 10 + bin_two % 10 + rem) % 2;
      rem = (bin_one % 10 + bin_two % 10 + rem) / 2;
      bin_one = bin_one/10;
      bin_two = bin_two/10;
   }
   
   if(rem!=0)
      sum[i++] = rem;

   i--;
   cout<<endl<<t1<<" + "<<t2<<" = ";

   while(i>=0)
      cout<<sum[i--];

   return 0;
}

Here is its sample run with user input, 101010 as first and 110111 as second binary number:

c++ program add binary numbers

Add Binary Numbers using User-defined Function

Here is another program that does the same task as of previous two programs, but using a user-defined function named addBinNums(), that takes two arguments. One for first binary number and second for second binary number entered by user at run-time.

#include<iostream>
using namespace std;

int i=0, sum[16];
void addBinNums(int, int);
int main()
{
   long int bin_one, bin_two;
   cout<<"Enter First Binary Number: ";
   cin>>bin_one;
   cout<<"Enter Second Binary Number: ";
   cin>>bin_two;

   addBinNums(bin_one, bin_two);

   cout<<endl<<"Sum = ";
   while(i>=0)
      cout<<sum[i--];

   return 0;
}
void addBinNums(int b1, int b2)
{
   int r=0;
   while(b1 !=0 || b2 !=0)
   {
      sum[i++] = (b1 % 10 + b2 % 10 + r) % 2;
      r = (b1 % 10 + b2 % 10 + r) / 2;
      b1 = b1/10;
      b2 = b2/10;
   }
   if(r!=0)
      sum[i++] = r;
   i--;
}

Here is its sample run with user input, 110111 and 100011 as first and second binary numbers:

c++ binary number addition using function

In above program, the statement int i=0, sum[16]; is declared globally, that is outside of both (main() and addBinNums()) the functions. So that, we can use these two variables throughout the program along with its updated values.

C++ Online Test


« Previous Program Next Program »

Follow/Like Us on Facebook




Subscribe Us on YouTube