Write a program to input ten numbers in an array by using scanner class. Search for a number in the array by using linear search technique. If found display "Search Successful " and print the position of the element in an array, or else display the message "Search Unsuccessful "
Answers
import java.util.Scanner;
public class LinearSearching {
// For linear searching and returning results.
static String linearSearch(int[ ] array, int searchElement) {
for (int i = 0; i < array.length; i++)
if (array[i] == searchElement)
return "Search Successful,\nFound At Index - " + i + ".";
return "Search Unsuccessful.";
}
public static void main(String[ ] args) {
// Declaration of array of 10 elements.
int[ ] array = new int[10];
// Accepting number into the array.
System.out.println("Enter 10 numbers - ");
Scanner sc = new Scanner(System.in);
for (int i = 0; i < array.length; i++)
array[i] = sc.nextInt( );
// Accepting the search element and printing the results.
System.out.print("Enter the number to be searched - ");
System.out.println(linearSearch(array, sc.nextInt( )));
}
}