Mon Sep 27 2021

Linear Search

File Name: linear-search.java

import java.io.*;
import java.util.Scanner;

class search {

	/* Constructor of the class */
	search(int list[], int srchdata) {
		int flag = 0;
		for(int data: list) {
			if(data == srchdata) {
				System.out.println(srchdata+" found on the list!");
				flag = 1;

				/* Terminate 'for' loop */
				break;
			}
		}
		if(flag == 0)
			System.out.println(srchdata+" not found on the list!");
	}
}
										
class linersearch {
	public static void main(String args[ ]) {
		int list[ ] = {5,9,8,1,6,4,2,7,3,0};
		Scanner input = new Scanner(System.in);
		System.out.println("Enter an number to search:");
		new search(list, Integer.parseInt(input.nextLine()));
	}
}



/* Output */
Enter an number to search:
22

22 not found on the list!

/* -------------------------------- */

Enter an number to search:
2

2 found on the list!
Reference:

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.