Q:

Write a Java program to find the index of an array element

belongs to collection: Array Programs in Java with Examples

0

Write a Java program to find the index of an array element

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

public class Main {
       public static int  findIndex (String[] myarray, String value) {
        if (myarray == null) return -1;
        int len = myarray.length;
        int i = 0;
        while (i < len) {
            if (myarray[i] == value) return i;
            else i=i+1;
        }
        return -1;
    }
    public static void main(String[] args) {
      String [] names = {"adnan","ahmed","abdullah","mohammad","john"};
      System.out.println("Index position of adnan is: " + findIndex(names, "adnan"));
      System.out.println("Index position of mohammad is: " + findIndex(names, "mohammad"));
      System.out.println("Index position of yasin is: " + findIndex(names, "yasin"));
       }
}

need an explanation for this answer? contact us directly to get an explanation for this answer
need an explanation for this answer? contact us directly to get an explanation for this answer

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..

public class Javaexcercise {
       public static int  findIndex (int[] myarray, int t) {
        if (myarray == null) return -1;
        int len = myarray.length;
        int i = 0;
        while (i < len) {
            if (myarray[i] == t) return i;
            else i=i+1;
        }
        return -1;
    }
    public static void main(String[] args) {
      int[] my_array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
      System.out.println("Index position of 2 is: " + findIndex(my_array, 2));
      System.out.println("Index position of 7 is: " + findIndex(my_array, 7));
      System.out.println("Index position of 6 is: " + findIndex(my_array, 9));
       }
}

Result:

Index position of 2 is: 1

Index position of 7 is: 6

Index position of 6 is: 8

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (2)

Array Programs in Java with Examples

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a Java program to calculate the average valu... >>
<< Write a Java program to sum values of an array...