Write a Java program to find the index of an array element
belongs to collection: Array Programs in Java with Examples
All Answers
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
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 answertotal answers (2)