Java Program to find Index of Specific element in the array:
The above diagram depicts array of size 5, if we want to find at which location number 50 is stored in the array, So we can find an index/ location of 50 with the help of this program. Here Index of 50 is ‘4’ so the program must return 4 as an output.
Algorithm/Program Explanation.
- Start
- Create Index method with parameters.
- public static int index(int array[], int temp)
- where temp is variable whose index is to be found.
- Store the length of array in variable length.
- int length=array.length;
- check for index with while loop
- while(i<length)
- if(array[i]==temp) return i//return index when array[i]=temp;
- else(i=i+1)
- Given array input
- int array[]={10,20,30,40,50};
- print index of an elements;
- end
Example 1: Taking Static Input
import java.util.*;
public class findindex()
{
public static int index(int array[],int temp){
if(array==null)return 0;
int length=array.length;
int i=0;
while(i<length)
{
if(array[i]==temp) return i;
else(i=i+1)
}
return 0;
}
public static void main (String args[]){
int array={10,20,30,40,50};
System.out.println("Index of Array Element 50 is" +index(array,50));
}
}
Output:
Index of Array Element 50 is 4
Example 2: Taking Input from User
- Start
- Create Index method with parameters.
- public static int index(int array[], int temp)
- where temp is variable whose index is to be found.
- Store the length of array in variable length.
- int length=array.length;
- check for index with while loop.
- while(i<length)
- if(array[i]==temp) return i//return index when array[i]=temp;
- else(i=i+1)
- Given array input
- int size;
- Scanner sc=new Scanner(System.in);
- size=sc.nextInt();
- int array[]=new int[size];
- using for loop take input to array
- for(int i=0;i<size;i++){
- array[i]=sc.nextInt();}
- print index of an elements;
- end
import java.util.*;
public class findindex()
{
public static int index(int array[],int temp){
if(array==null)return 0;
int length=array.length;
int i=0;
while(i<length)
{
if(array[i]==temp) return i;
else(i=i+1)
}
return 0;
}
public static void main (String args[]){
int size;
System.out.println(Enter Number of Array Elements:);
Scanner sc=new Scanner(System.in);
size=sc.nextInt();
System.out.println("Enter Elements to Array:");
for(int i=0;i,size;i++){
array[i]=sc.nextInt();
}
System.out.println("Index of Array Element 50 is" +index(array,50));
}
}
Output:
Enter Number of Array Elements:
5
Enter Elements to Arrays:
10 20 30 40 50
Index of Array Element 50 is 4
Java Program to find the Index of Specific element in the array: Question can be asked in this topic
- Write a program to find the index of the given number in array?
- Find Index of element in user-defined array?
- State different ways to find the index of the element in an array?
- Given is an array of size 6 find index of Number 29 in array?
- In this type of question just write the logic, No need of defining an array.