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


Introduction

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..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

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

Result

java techstudy.org

     





Related Topics




Popular Posts