-2

I have to sum binary numbers, I'm using reverse loop like we actually sum using pen & paper. So there is this hard-coded array of two integers whose length I have made equal in order to avoid any discrepancy. I'm checking whether sum & carry value matches then output should be made so & so otherwise so & so. Check code below.

My question is why am I getting error on running as to Array Index Out of Bounds -1, even after a successful compilation.

public class binary{

static int sum, carry;
static int output = 0;


    public static void main(String args[])
    {
        int[] a = {1,1,0,1,1,0,0,1,0,0,1};
        int[] b = {1,0,0,0,0,0,0,0,1,0,1};

        for(int i = 10; i >= 0; i--)
        {
            if(a[i] == 0 && b[i] == 0)
            {
                sum = 0;
                carry = 0;

            }
            if(a[i] == 0 && b[i] == 1)
            {
                sum = 1;
                carry = 0;

            }
            if(a[i] == 1 && b[i] == 0)
            {
                sum = 1;
                carry = 0;

            }
            if(a[i] == 1 && b[i] == 1)
            {
                sum = 0;
                carry = 1;

            }
            if(carry == 1)
            {
                carry += a[i-1] + b[i-1];
                output = carry;
            }
            else
            {
                output += a[i] + b[i];
                output = sum;
            }
            System.out.print(output); 
        } 
    }
}
Anurag Joshi
  • 300
  • 1
  • 12

2 Answers2

0
 if(carry == 1)
    {
        carry += a[i-1] + b[i-1];
        output = carry;
    }

This is the part that is causing the array out of bound exception..since for i=0 the carry will contain a[-1]+b[-1] which are of course out of bound(0 and 10 being the bounds)

Pratyay
  • 1,291
  • 14
  • 23
0
carry += a[i-1] + b[i-1];

If i is 0 then you will get index -1.

Aidin
  • 1,230
  • 2
  • 11
  • 16
fg78nc
  • 4,774
  • 3
  • 19
  • 32