The Program in C++ to Add two Binary Numbers is given below:
#include <iostream>
#include <string>
using namespace std;
string addBinary(string a, string b) {
string result = "";
int s = 0;
int i = a.size() - 1, j = b.size() - 1;
while (i >= 0 || j >= 0 || s == 1) {
s += ((i >= 0) ? a[i] - '0' : 0);
s += ((j >= 0) ? b[j] - '0' : 0);
result = char(s % 2 + '0') + result;
s /= 2;
i--; j--;
}
return result;
}
int main() {
string a, b;
cout<< "Hello Codeauri Family, Please enter value of a :\n";
cin>>a;
cout<< "Hello Codeauri Family, Please enter value of b :\n";
cin>>b;
cout << "The sum of the two binary numbers is: " << addBinary(a, b) << endl;
return 0;
}
Output:
Hello Codeauri Family, Please enter value of a :
4
Hello Codeauri Family, Please enter value of b :
5
The sum of the two binary numbers is: 1
Pro-Tips💡
This program adds two binary numbers input by the user.
It uses a function called “addBinary” that takes in two binary numbers as strings and returns their sum as a string.
The function uses a while loop to iterate through the digits of the binary numbers starting from the rightmost digit.
At each iteration, the digits are added and the sum is calculated by taking the remainder when divided by 2.
The carry is calculated by taking the floor division of the sum by 2. The result string is built by adding the sum and carry to the left of the previously calculated result.
The result of the addBinary function is then displayed using the cout statement in the main function.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.