Medium Searching

Linear search

The first INPUT () is how many numbers follow. Read them, then read the target. DISPLAY the index of the first element equal to the target (the first index is 1), or 0 if the target is not in the list.

Input (one value per INPUT ())Expected output
5 4 8 15 16 23 153
3 7 7 7 71

Check runs all 3 tests. Press Run to try the program yourself: a box asks for each INPUT ().

Output


        
        
      

Variables

Show a solution
count ← INPUT ()
nums ← []
REPEAT count TIMES
{
   APPEND (nums, INPUT ())
}
target ← INPUT ()
found ← 0
i ← 1
REPEAT UNTIL (i > LENGTH (nums) OR found ≠ 0)
{
   IF (nums[i] = target)
   {
      found ← i
   }
   i ← i + 1
}
DISPLAY (found)

Teachers: sign in as a teacher to add this exercise to a class, graded automatically.

Frequently asked questions

How do I solve this exercise?

Complete the starter code in the editor, press Run to try it (type values when INPUT () asks), then press Check to run every test. Step shows the program line by line with its variables.

Where is the solution?

Under the editor, in Show a solution. Try the exercise first: comparing your code with the solution afterwards is a good way to learn another approach.

AP is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this site.