4. Write a program to find array index

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("[14,12,9,15,17,21,23,5,8,25]");
        System.out.println("Enter a number that contains in the given array:\n");
        Scanner scanner=new Scanner(System.in);
        int value=scanner.nextInt();
        int[] numbers={14,12,9,15,17,21,23,5,8,25};
        int index=findArrayIndex(numbers,value);
        System.out.println("Array index is: "+index);

    }
    public static int findArrayIndex(int[] arr, int n){
        for(int i=0;i<arr.length;i++){
            if(arr[i]==n){
                return i;
            }
        }
        return -1;

    }
}
Output:
[14,12,9,15,17,21,23,5,8,25]
Enter a number that contains in the given array:
17
Array index is: 4

[14,12,9,15,17,21,23,5,8,25]
Enter a number that contains in the given array:
55 //if input number which is not listed in array
Array index is: -1
about author

admin

salmansrabon@gmail.com

If you like my post or If you have any queries, do not hesitate to leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *