Logic Errors - Computer Science

Card 0 of 2

Question

Consider the following code:

public static int\[\] del(int\[\] a,int delIndex) {

if(delIndex < 0 || delIndex >= a.length) {

return null;

}

int\[\] ret = new int\[a.length - 1\];

for(int i = 0; i < a.length; i++) {

if(i != delIndex) {

ret\[i\] = a\[i\];

}

}

return ret;

}

What is the error in the code above?

Answer

The problematic line in the code above is the one that reads:

ret\[i\] = a\[i\];

This is going to work well until the end of the array. The variable i is going to go for the length of the array a. However, the array ret is one less in length. This means that you will overrun your array, getting an ArrayIndexOutOfBoundsException at the very end of the looping. You would need to implement two indices—one of which will not be incremented on that one time when you skip the element that is removed from the array.

Compare your answer with the correct one above

Question

What is wrong with this loop?

int i = 0;

int count = 20;

int\[\] arr = \[1, 3, 4, 6, 8, 768, 78, 9\]

while (i < count) {

if (i > 0) {

arr\[i\] = count;

}

if (i < 15) {

System.out.println("HEY");

}

}

Answer

The loop is infinite because i never gets incremented to become greater than count.

The loop in this case is,

while (i < count) {

if (i > 0) {

arr\[i\] = count;

}

and the error occurs because there is no terminating factor in the while loop. A terminating factor would be,

while(i<count){

if(i>0, i<10, i++){

arr\[i\] = count;

}

Compare your answer with the correct one above

Tap the card to reveal the answer