Linear Search

Lab Java Beginner 10 points

Read n integers and a target. Print the index of the first occurrence of the target, or -1.

Input

n, the integers, then the target.

Output

An index.

Example

Input

5
4 8 15 16 23
15

Output

2
Sample input available Sample output available
Editor
Java

Hints

Use an index loop so you know where the match is.

Solution explanation

Linear search checks each element in turn - simple, and works on unsorted data.

Show solution
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        int target = sc.nextInt();
        int index = -1;
        for (int i = 0; i < n; i++) {
            if (a[i] == target) {
                index = i;
                break;
            }
        }
        System.out.println(index);
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD