Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // OLA206 BY student name, CSCI2170-sec, Due: mm/dd/yy
- // PROGRAM ID: binadd.cpp / Binary Number Addition Program
- // AUTHOR: student name
- // INSTALLATION: MIDDLE TENNESSEE STATE UNIVERSITY
- // REMARKS: Adds two or more binary numbers appearing as command-line
- // arguments. The resulting sum is sent to stdout. The arguments are
- // assumed to be well-formed (valid) binary numbers; no error checking
- // is performed on the arguments.
- //
- // For example: binadd 100 1 1101 0
- // should print 10010
- //
- // . 1 . 2 . 3 . 4 . 5 . 6 . 7 .
- //3456789012345678901234567890123456789012345678901234567890123456789012345
- #include <iostream>
- #include <cstring>
- using namespace std;
- const int MAX_DIGITS = 36; // Maximum digits in (output) sum
- bool Badd( const char augend[], const char addend[], char sum[] );
- // IN IN OUT
- 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 were supplied.
- if (argc < 3)
- {
- cout << "Error: insufficient arguments.\n";
- return 1;
- }
- // Add together the first two binary numbers on the command-line.
- noError = Badd( argv[1], argv[2], sum );
- // Add any 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 answer on standard output.
- if (noError)
- cout << sum << endl;
- else
- cout << 'E' << endl;
- return 0;
- } // end main
- 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 the sum of augend + addend.
- // Returns true if successful in addition, false otherwise.
- {
- int x, carry = 0;
- for(int i = 0; i < argc-1; i++)
- {
- if(augend[i]==1 && addend[i]==1 && carry ==1)
- {
- sum[x]=1;
- carry=1;
- }
- else if(augend[i]==1 && addend[i]==1 && carry ==0)
- {
- sum[x]=0;
- carry=1;
- }
- else if(augend[i]==0 && addend[i]==1 && carry ==0)
- {
- sum[x]=1;
- carry=0;
- }
- else if(augend[i]==0 && addend[i]==1 && carry ==1)
- {
- sum[x]=0;
- carry=1;
- }
- else if(augend[i]==1 && addend[i]==0 && carry ==1)
- {
- sum[x]=0;
- carry=1;
- }
- else if(augend[i]==1 && addend[i]==0 && carry ==0)
- {
- sum[x]=1;
- carry=0;
- }
- else if(augend[i]==0 && addend[i]==0 && carry ==1)
- {
- sum[x]=1;
- carry=0;
- }
- else if(augend[i]==0 && addend[i]==0 && carry ==0)
- {
- sum[x]=0;
- carry=0;
- }
- x++;
- }
- sum[0] = '0';
- sum[1] = '\0';
- return true;
- } // end Badd
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement