Write a program using one-dimensional array that searches a number if it is found on the list of the given 5 input numbers and locate its exact location in the list.
Sample input/output dialogue:
Enter a list of numbers: 5 4 8 2 6 Enter a number to be searched: 2 2found in location 4
import java.util.Scanner;
public class Answer {
static int find(int[] arr , int el) {
for (int i = 0; i < arr.length; i++) {
if (el == arr[i]) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] array = new int[5];
System.out.println("Enter a list of numbers: ");
for (int i = 0; i < array.length; i++) {
array[i] = scanner.nextInt();
}
System.out.println("Enter a number to be searched: ");
int el = scanner.nextInt();
int ans = find(array, el);
if (ans == -1) {
System.out.println("Element not found");
} else {
System.out.println(el + " found in location " + (ans + 1));
}
}
}
Comments
Leave a comment