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);
}
}
}