Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Someone please help me find the bug in this program. void binarySubtraction(int

ID: 3838171 • Letter: S

Question

Someone please help me find the bug in this program.

void binarySubtraction(int (&number1)[16], int (&number2)[16], int (&result)[16])
{

int barrow = 0;
for(int i = 0; i < 16; i++)
{
if(barrow == 0 && number1[i] == 0 && number2[i] == 0)
{
result[i] = 0;
}
else if(barrow == 0 && number1[i] == 0 && number2[i] == 1)
{
barrow = 1;
result[i] = 1;
}
else if(barrow == 0 && number1[i] == 1 && number2[i] == 1)
{
result[i] = 0;
}
else if(barrow == 0 && number1[i] == 1 && number2[i] == 0)
{
result[i] = 1;
}
else if(barrow == 1 && number1[i] == 0 && number2[i] == 0)
{
result[i] = 1;
}
else if(barrow == 1 && number1[i] == 1 && number2[i] == 0)
{
barrow = 0;
result[i] = 0;
}
else if(barrow == 1 && number1[i] == 1 && number2[i] == 1)
{
result[i] = 1;
}
else if(barrow == 1 && number1[i] == 0 && number2[i] == 1)
{
result[i] = 1;
}

}
}

Explanation / Answer

Replace condition in for loop with for( int i=15; i>=0 ; i--)

The bug is that in for loop, you are taking starting i=0 to 15. This means you are starting subtraction from Most Significant bit (Bits from right to left). In that case borrow is propagating from right to left. This is not correct.

Bitwise subtraction has to done from least significant bit to Most significant bit ( Bits from left to right).

n1= 8 = 00001000

n2= 11=00001011, The subtraction should start from LSB ( i.e 0 and 1).

//simpler version

Otherwise, instead of using all those if conditions, try this

for(i = 7; i >= 0; i--){
   result[i] = number1[i] - number2[i];
   if(diff[i] < 0){
       number1[i-1] = number1[i-1] - 1;
   }
   result[i] = fabs(result[i]%2);
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote