1. Trace the flow of the following linear search loop, where values contains the
ID: 3815911 • Letter: 1
Question
1. Trace the flow of the following linear search loop, where values contains the elements 80 90 100 120 110.
Show two columns, for pos and found.
Repeat the trace when values contains 80 90 100 70.
int searchedValue = 100;
int pos = 0;
boolean found = false;
while (pos < values.length && !found) {
if (values[pos] == searchedValue) {
found = true;
} else {
pos++;
}
}
if (found) {
System.out.println("Found at position: " + pos);
} else {
System.out.println("Not found");
}
2. Trace the flow of the loop from question 1, where values contains the elements 80 90 100 120 110.
Show two columns, for pos and found.
Repeat the trace when values contains the elements 80 90 120 70.
Explanation / Answer
int searchedValue = 100;
int pos = 0;
boolean found = false;
while (pos < values.length && !found) {
if (values[pos] == searchedValue) {
found = true;
} else {
pos++;
}
}
if (found) {
System.out.println("Found at position: " + pos);
} else {
System.out.println("Not found");
}
80 90 100 120 110.
searchedValue = 100;
pos found
0 false
1 false
2 true
loop break here and print Found at position: 2
80 90 120 70
searchedValue = 100;
pos found
0 false
1 false
2 false
3 false
loop break here and print Not found
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.