79.2k views
3 votes
Programming challenge description: Write a program that, given two binary numbers represented as strings, prints their sum in binary. The binary strings are comma separated, two per line. The final answer should not have any leading zeroes. In case the answer is zero, just print one zero i.e. 0 Input: Your program should read lines from standard input. Each line contains two binary strings, separated by a comma and no spaces. Output: For each pair of binary numbers print to standard output their binary sum, one per line.

1 Answer

4 votes

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

Step-by-step 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.

User Soulemane Moumie
by
5.9k points