Write a program to initialize an integer array with values and check if a given number is present in the array or not. If the number is not found, it will print -1 else it will print the index value of the given number in the array Ex1) Array elements are {1,4,34,56,7} and the search element is 90 O/P: -1 Ex2)Array elements are {1,4,34,56,7} and the search element is 56 O/P: 4.
Write a program to initialize an integer array with values and check if a given number is present in the …
Share
public class Main { public static void main(String[] args) { int[] haystack = {1,4,34,56,7}; int needle = 7;//search for element in array int index = -1; for (int i = 0; i < haystack.length; i++) { if (haystack[i] == needle) { index = i + 1; break; } } System.out.println("At position :" + index); } }