Java bootcamp · Lab 36

Linear search

easyArrays10 minLesson: Arrays

Read the question, write Java on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read n, n ints, then target. Print 0-based index or -1.

Examples

Example 1
Input
4
4 8 15 16
15
Output
2
Hint
  1. Loop and compare.
Show correct code

Peek only after you have tried. You can still Check your own version.

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int[] a = new int[n];
    for (int i = 0; i < n; i++) a[i] = in.nextInt();
    int target = in.nextInt();
    int idx = -1;
    for (int i = 0; i < n; i++) if (a[i] == target) { idx = i; break; }
    System.out.println(idx);
  }
}
Main.javaJava 21 · javac · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.