Search code examples
c++turbo-c++

adding two binary numbers(integer array)


I have done this program to add two binary numbers of the same length stored in an integer array and store the sum in a new integer array. But due to some logical error, it does not show the desired output.

#include <conio.h>
#include <iostream.h>

void main() {
    clrscr();
    int a[] = {1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1,
               1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1};
    int b[] = {1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1,
               1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0};
    int temp[100];
    int carry = 0, p = 35;
    for(int i = 34; i >= 0; i--) {
        if(a[i] + b[i] + carry == 0) {
            temp[p] = 0;
            carry = 0;
            p--;
        }
        if((a[i] + b[i] + carry) == 1) {
            temp[p] = 1;
            carry = 0;
            p--;
        }
        if((a[i] + b[i] + carry) == 2) {
            temp[p] = 0;
            carry = 1;
            p--;
        }
        if((a[i] + b[i] + carry) > 2) {
            temp[p] = 1;
            carry = 1;
            p--;
        }
    }
    for(int pop = 0; pop < 36; pop++) cout << temp[pop];
    getch();
}

the expected output is:

110100101001100101101010110101011111

actual output is:

101100110011011101011011101011011111

Solution

  • The issue in your code is you have a set of separate if statements which each modify carry, if carry is changed in such a way to alter the result of the subsequent if statements then multiple if statement bodies will be executed.

    The simple fix is to change your last 3 ifs to else if.

    You also need to add the final carry bit to your output:

    temp[0] = carry;
    for(int pop = 0; pop < 36; pop++) cout << temp[pop];
    

    However your code could be greatly simplified using a swtich statement. Simpler code is generally less buggy and easier to understand:

    for(int i = 34; i >= 0; i--, p--) {
        switch(a[i] + b[i] + carry) {
        case 0:
            temp[p] = 0;
            carry = 0;
            break;
        case 1:
            temp[p] = 1;
            carry = 0;
            break;
        case 2:
            temp[p] = 0;
            carry = 1;
            break;
        case 3:
            temp[p] = 1;
            carry = 1;
            break;
        default:
            // should never be reached with inputs of 0 or 1
            throw std::invalid_argument("invalid input");
        }
    }
    

    This code could be simplified even further using bit manipulations to remove all branches and set the bits directly but I'll leave that as an exercise for the reader hint.