Hi the code to answer exercise 61 is below However it is inc
Hi, the code to answer exercise 6.1 is below. However, it is incorrect because \"The incorrect value 4 was found in variable count (should be 5).\" Please edit the code below so that the value 5 is found in variable count.
for (count = 0; count < theArray.length; count++) {
if (theArray[count] == targetnum) {
slot = count;
break;
}
}
if(count == theArray.length) {
System.out.println(\"Search element was not found\");
}
else {
System.out.println(\"else\");
}
Solution
As per the instruction number 3 in the given problem, when a loop terminates it must contain the number of comparsons to find tthe value and as per instruction number 6, if the value was found in slot 3 it took 3+1 or 4 comparisions to find it.
Now, you are starting you for loop from count = 0 and compairing element int theArray with target num and if they are equal you simply store the count in the slot which is incorrect over here. The slot should be the current index plus 1 i.e., count+1. As shown below:
for (count = 0; count < theArray.length; count++) {
if (theArray[count] == targetnum) {
slot = count+1;
break;
}
}
