Answer:
The program to this question can be given as:
Program:
#include<iostream> //include header file
using namespace std;
string add(string a, string b) //define add function
{ //declare variable
string result = "";
int sum = 0,k,l;
cahr x;
k= a.size() - 1;
l = b.size() - 1;
while (k>= 0 || l>= 0 || sum == 1) //loop
{
//addition
sum= sum+ ((k >= 0)? a[k] - '0': 0);
sum= sum+ ((l >= 0)? b[l] - '0': 0);
x=sum%2;
result=(x+'0') +result;
// Compute carry
sum =sum/ 2;
// Move to next digits
k--;
l--;
}
return result; //return value
}
int main() //main method
{
string a,b; //string variable
cout<<"Enter first binary digit: "; //message.
cin>>a; //input from user
cout<<"Enter Second binary digit: "; //message.
cin>>b; //input from user
cout <<"Addition :"<<add(a, b)<<endl; //print addition
return 0;
}
Output:
Enter first binary digit: 1101
Enter Second binary digit: 100
Addition :10001
Explanation:
In the above c++ program first, we include the header file. Then we define the add function in the add function we add two binary digits by passing value as arguments. In this function, we define a variable that is used on the addition of binary numbers. In this function we define the loop in the loop we check if two binary number is 1 then it will print 0 and pass 1 as the carry. after performing addition it will return value. In the main function, we take two binary numbers from the user and pass the value to the function and print function return value.