StackTips

Linear / Sequential Search Example in Java

stacktips avtar

Written by

Editorial,  2 min read,  2.87K 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

Beginner's Guide to Java Collections

This course covers the fundamentals of java collections framework covering different data structures in Java to store, group, and retrieve objects.

>> CHECK OUT THE COURSE
stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.

Related posts

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!