Question

I am trying to write a c++ program that will add two binary numbers that are...

I am trying to write a c++ program that will add two binary numbers that are entered into the command line. I cannot get the program to send anything to stdout. code attached.

int main(int argc, char *argv[])
//           IN       IN
{
   char partialSum[MAX_DIGITS + 1]; //partial sum of the binary numbers
   char sum[MAX_DIGITS + 1];       //sum of the binary numbers
   bool noError;       //no error flag
  
   //Exit if insufficient arguments passed to function
   if (argc < 3)
   {
       cout << "Insufficient arguments passed" << endl;
       return 1;
   }
  
   //Add the first two binary numbers on the command line.
   noError = Badd(argv[1], argv[2], sum);
  
   //Add additional binary numbers to the partial sum
   for (int counter = 3; noError && counter < argc; counter++)
   {
       strcpy(partialSum, sum);
       noError = Badd(partialSum, argv[counter], sum);
   }
  
   //Print the answer to standard output
   if (noError)
   {
       for (int counter = 0; counter < strlen(sum); counter++)
       {
           cout << sum[counter];
       }
       cout << endl;
   }
   else
       cout << 'E' << endl;
      
   return 0;
}// end main function

bool Badd(const char augend[], const char addend[], char sum[])
//           IN                   IN                   OUT
//PRE: augend and addend are strings representing valid binary numbers
//POST: sum is a string representing augend + addend
//returns true if addition is successful and false if otherwise
{
   char carry = '0'; //Carry after addition
   int lsl; //Longer string length
   int augl = strlen(augend) - 1; //length of augend string
   int addl = strlen(addend) - 1; //length of addend string
   int augDigit; //element of augend string
   int addDigit; //element of addend string
  
   if (strlen(augend) > strlen(addend))
   {
       lsl = strlen(augend);
   }
  
   else if(strlen(augend) < strlen(addend))
   {
       lsl = strlen(addend);
   }
  
   else if (strlen(augend) == strlen(addend))
   {
       lsl = strlen(augend);
   }
  
   sum[lsl] = '\0';
   for (int counter = lsl - 1; counter < 0; counter--)
   {
       augDigit = (augl < 0) ? '0' : augend[augl--];
       addDigit = (addl < 0) ? '0' : addend[addl--];
      
       if (carry == '0' && augend[augDigit] == '0' && addend[addDigit] == '0')
       {
           sum[counter] = '0';
           carry = '0';
       }
      
       else if(carry == '1' && augend[augDigit] == '0' && addend[addDigit] == '0')
       {
           sum[counter] = '1';
           carry = '0';
       }
      
       else if(carry == '0' && augend[augDigit] == '1' && addend[addDigit] == '0')
       {
           sum[counter] = '1';
           carry = '0';
       }
      
       else if(carry == '0' && augend[augDigit] == '0' && addend[addDigit] == '1')
       {
           sum[counter] = '1';
           carry = '0';
       }
       else if(carry == '1' && augend[augDigit] == '1' && addend[addDigit] == '0')
       {
           sum[counter] = '0';
           carry = '1';
       }
      
       else if(carry == '0' && augend[augDigit] == '1' && addend[addDigit] == '1')
       {
           sum[counter] = '0';
           carry = '1';
       }
      
       else if(carry == '1' && augend[augDigit] == '0' && addend[addDigit] == '1')
       {
           sum[counter] = '0';
           carry = '1';
       }
      
       else if(carry == '1' && augend[augDigit] == '1' && addend[addDigit] == '1')
       {
           sum[counter] = '1';
           carry = '1';
       }
   }
  
   if (strlen(sum) > MAX_DIGITS)
       return false;
  
   else
       return true;
} //end of Badd function

0 0
Add a comment Improve this question Transcribed image text
Answer #1

This is the updated code that prints the output, just made use of string class of c++

#include<bits/stdc++.h>
using namespace std;

#define MAX_DIGITS 32
string ans;
string addBinary(string a, string b)
{
string result = ""; // Initialize result
int s = 0; // Initialize digit sum
  
// Travers both strings starting from last
// characters
int i = a.size() - 1, j = b.size() - 1;
while (i >= 0 || j >= 0 || s == 1)
{
// Comput sum of last digits and carry
s += ((i >= 0)? a[i] - '0': 0);
s += ((j >= 0)? b[j] - '0': 0);
  
// If current digit sum is 1 or 3, add 1 to result
result = char(s % 2 + '0') + result;
  
// Compute carry
s /= 2;
  
// Move to next digits
i--; j--;
}
return result;
}
bool Badd(const char augend[], const char addend[])
// IN IN OUT
//PRE: augend and addend are strings representing valid binary numbers
//POST: sum is a string representing augend + addend
//returns true if addition is successful and false if otherwise
{
string a = "",b="",c;
for(int i=0;i<strlen(augend);i++)
    a = a + augend[i];
for(int i=0;i<strlen(addend);i++)
    b = b + addend[i];

ans = addBinary(a,b);
return true;

} //end of Badd function
int main(int argc, char *argv[])
// IN IN
{
char partialSum[MAX_DIGITS + 1]; //partial sum of the binary numbers
char sum[MAX_DIGITS + 1]; //sum of the binary numbers
bool noError; //no error flag

//Exit if insufficient arguments passed to function
if (argc < 3)
{
cout << "Insufficient arguments passed" << endl;
return 1;
}
  
//Add the first two binary numbers on the command line.
noError = Badd(argv[1], argv[2]);
  

  
//Print the answer to standard output
if (noError)
{
cout << ans ;
cout << endl;
}
else
cout << 'E' << endl;
  
return 0;
}// end main function


Thank you, please upvote.

Add a comment
Know the answer?
Add Answer to:
I am trying to write a c++ program that will add two binary numbers that are...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a C/C++ program that simulate a menu based binary number calculator. This calculate shall have the following three...

    Write a C/C++ program that simulate a menu based binary number calculator. This calculate shall have the following three functionalities: Covert a binary string to corresponding positive integers Convert a positive integer to its binary representation Add two binary numbers, both numbers are represented as a string of 0s and 1s To reduce student work load, a start file CSCIProjOneHandout.cpp is given. In this file, the structure of the program has been established. The students only need to implement the...

  • Can someone help with this C++ code. I am trying to compile and I keep running...

    Can someone help with this C++ code. I am trying to compile and I keep running into these 4 errors. #include <iostream> #include <cassert> #include <string> using namespace std; typedef int fsm_state; typedef char fsm_input; bool is_final_state(fsm_state state) { return (state == 3) ? true : false; } fsm_state get_start_state(void) { return 0; } fsm_state move(fsm_state state, fsm_input input) { // our alphabet includes only 'a' and 'b' if (input != 'a' && input != 'b') assert(0); switch (state) {...

  • Write a C++ program In this assignment you will complete the definition of two functions that...

    Write a C++ program In this assignment you will complete the definition of two functions that implement the repeated squaring algorithm described in the Stamp textbook on pages 98-99. Note that your implementation should not use the pow() function, the powl() functions, or any other built-in exponentiation functions. program4-driver.cpp - This file contains a completed main() function that serves as the driver to parse the command line, pass the values to the powerModN() function, and print the result. Make no...

  • ***************Fix code recursive function #include <iostream> #include <cctype> #include <string> using namespace std; void printUsageInfo(string executableName)...

    ***************Fix code recursive function #include <iostream> #include <cctype> #include <string> using namespace std; void printUsageInfo(string executableName) { cout << "Usage: " << executableName << " [-c] [-s] string ... " << endl; cout << " -c: turn on case sensitivity" << endl; cout << " -s: turn off ignoring spaces" << endl; exit(1); //prints program usage message in case no strings were found at command line } string tolower(string str) { for(unsigned int i = 0; i < str.length(); i++)...

  • Can you all fix this coding below, if so "ASAP" would be great? Write a program...

    Can you all fix this coding below, if so "ASAP" would be great? Write a program that prompts the user to input a string and outputs the string in uppercase letters using dynamic arrays. int main() {​ char *str; ​ ​ int strLen;​ int len;​ char ch;​ ​ int i;​ ​ cout << "Enter the size of the string: ";​ cin >> strLen;​ cout << endl;​ ​ cin.get(ch);​ ​ str = new char[strLen + 1];​ ​ cout << "Enter a...

  • C++ problem. hi heys, i am trying to remove beginning and the end whitespace in one...

    C++ problem. hi heys, i am trying to remove beginning and the end whitespace in one file, and output the result to another file. But i am confused about how to remove whitespace. i need to make a function to do it. It should use string, anyone can help me ? here is my code. #include <iostream> #include <iomanip> #include <cstdlib> #include <fstream> using namespace std; void IsFileName(string filename); int main(int argc, char const *argv[]) { string inputfileName = argv[1];...

  • c++, I am having trouble getting my program to compile, any help would be appreciated. #include...

    c++, I am having trouble getting my program to compile, any help would be appreciated. #include <iostream> #include <string> #include <string.h> #include <fstream> #include <stdlib.h> using namespace std; struct record { char artist[50]; char title[50]; char year[50]; }; class CD { //private members declared private: string artist; //asks for string string title; // asks for string int yearReleased; //asks for integer //public members declared public: CD(); CD(string,string,int); void setArtist(string); void setTitle(string); void setYearReleased(int); string getArtist() const; string getTitle() const; int...

  • /// c ++ question plz help me fix this not a new code and explain to...

    /// c ++ question plz help me fix this not a new code and explain to me plz /// Write a function to verify the format of an email address: bool VeryifyEmail(char email[ ]); Do NOT parse the email array once character at a time. Use cstring functions to do most of the work. Take a look at the available cstring and string class functions on cplusplus website. Use a two dimensional array to store the acceptable top domain names:...

  • Convert C to C++ I need these 4 C file code convert to C++. Please Convert...

    Convert C to C++ I need these 4 C file code convert to C++. Please Convert it to C++ //////first C file: Wunzip.c #include int main(int argc, char* argv[]) { if(argc ==1){ printf("wunzip: file1 [file2 ...]\n"); return 1; } else{ for(int i =1; i< argc;i++){ int num=-1; int numout=-1; int c; int c1;    FILE* file = fopen(argv[i],"rb"); if(file == NULL){ printf("Cannot Open File\n"); return 1; } else{ while(numout != 0){    numout = fread(&num, sizeof(int), 1, file);    c...

  • Hello, I am trying to write this program and have received a "Segmentation Fault" error but...

    Hello, I am trying to write this program and have received a "Segmentation Fault" error but cannot seem to figure out where. I haven't been able to find it and have been looking for quite a while. The goal is to basically create a version of Conway's Game of Life. I am able to generate a table if the input values for rows and columns are equal, but if they are not I receive a segmentation fault and cannot continue...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT