Binary Addition C++

Hi, I am trying to add to two binary number arrays and storing the answer in the third array. I can’t understand why I am not getting the correct answer.
Here is the code;

#include <iostream>

using namespace std;

int main()
{
	int A[5] = {1, 1, 0, 1, 1}, B[5] = {0, 1, 0, 1, 1}, C[6] = {}, carry = 0;
	
	for(int i = 5; i >= 0; i--){
		if(i == 0){
		    C[i] = carry;
		}
		else{
		    C[i] = A[i - 1] + B[i - 1] + carry;
		    if(C[i] == 2){
		        C[i] = 0;
		        carry = 1;
		    }
		    else if(C[i] == 3){
		        C[i] = 1;
		        carry = 1;
		    }
		}
	}
	
	for(int i = 0; i < 6; i++){
	    cout << C[i];
	}
	
	return 0;
}

I will be very grateful for your help.

Well you need to set carry=0 after using it.
As it stands, once carry is set to 1, it will be 1 in ALL following calculations.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.