the incorrect value 99 was found in variable i (should be 30) Your Code ( with c
ID: 3738489 • Letter: T
Question
the incorrect value 99 was found in variable i (should be 30) Your Code ( with color highlights added ): for (int j = 0; j < arraydata.lenght ; j++ ){ if (arraydata[j]==targetvar){ i = j + 1; } } The Instructions: Exercise 6.1 : O(N) Loop A classic O(N) algorithm is linear search, where every item is looked at until the target is found Write a 'for' loop to search the array of integers arraydata, use the variable i and the .length property to control the loop Use an 'if' statement to find a match for the value in the variable targetvar When the loop terminates i MUST contain the number of comparisons to find the value That number must be +1 of the slot the item was found in, if the item was found in slot zero, it took one comparison to find it Do not declare i or initialize arraydata or targetvar it will be done for you. Write only a loop with an if inside and remember when the value was found in slot 3 it took 3+1 or 4 comparisons to find it
Explanation / Answer
the incorrect value 99 was found in variable i (should be 30) Your Code ( with color highlights added ):
for (int j = 0; j < arraydata.lenght ; j++ ){ if (arraydata[j]==targetvar){ i = j + 1; } }
The problem with above code is that,when arraydata might contain multiple instance of targetvar above problem might occur.You want to terminate the loop when first match is found. for e.g
arradata={1,4,3,6,4,8}
assume targetvar=4
two 4's
first at slot 1
second at slot 4
so if you execute your above code you will get i= j+1 = 4+1 =5 i.e comparisons of last match
but we want to terminate at first match so use below code:
Note: since questions only asks to write ONLY a loop and dont initialize and declare i,arraydata,targetvar ,i have answered as required.
code:
for (int j = 0; j < arraydata.lenght ; j++ )
{
if (arraydata[j]==targetvar)
{
i=j+1;
return i; //terminating the loop here since first match is found
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.