StackTips

Linear / Sequential Search Example in Java

stacktips avtar

Written by

Editorial,  2 min read,  2.79K views, updated on Sept. 17, 2023

Quick Java code snippet to show Linear / Sequential Search.

import java.util.Scanner;

public class LinearSearchExample {

	public static void main(String args[]) {
		int i, totalCount, search, inputArray[];

		Scanner scanner = new Scanner(System.in);

		System.out.println("Enter number of elements");
		totalCount = scanner.nextInt();
		inputArray = new int[totalCount];

		System.out.println("Enter " + totalCount + " integers");

		for (i = 0; i < totalCount; i++) {
			inputArray[i] = scanner.nextInt();
		}

		System.out.println("Enter value to find");
		search = scanner.nextInt();

		for (i = 0; i < totalCount; i++) {
			// Element found
			if (inputArray[i] == search) {
				System.out.println(search + " is present at location "
						+ (i + 1) + ".");
				break;
			}
		}

		// Element not in the input array
		if (i == totalCount) {
			System.out.println(search + " is not present in array.");
		}
	}
}

Output

Linear : Sequential Search Example in Java

Java Collection APIs

The Collections framework in Java defines numerous different data structures in which you can store, group, and retrieve objects.

>> CHECK OUT THE COURSE

Keep exploring

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!