write two method called findIndex and findLastIndex that search for a number in an array. they should take an int array and an int as parameters. findIndex should return the index of the first instance of the number in the array. findLastIndex should return the index of the last instance of the number in the array. They both should return -1 if the number is not found. Do not use any library methods
public class Main
{
public static void main(String[] args) {
//Declare the int array to search
int[] intArray = new int[]{ 1,15,3,47,5,7,8,5,10 };
//Call findIndex()
System.out.println(findIndex(intArray, 5));
//Call findILastndex()
System.out.println(findLastIndex(intArray, 5));
}
public static int findIndex(int[] array, int x)
{
//Get the length of array
int l = array.length;
//Variable to hold value of index if found and -1 if not
int index = 0 ;
//Loop equal to size of the array given starting from 0(begining)
for(int i = 0; i < l; i++)
{
//If int parameter given is equal to current value int the array assing its index to index variable
if(x == array[i])
{
index = i;
break; //Exit the loop
}
//If no match found assign -1
else
{
index = -1;
}
}
//Return index
return index;
}
public static int findLastIndex(int[] array, int x)
{
//Get the length of array and deduct 1 to start at last index
int l = array.length -1;
//Variable to hold value of index if found and -1 if not
int index = 0 ;
//Loop equal to size of the array given starting from the last index
for(int i = l; i >= 0; i--)
{
//If int parameter given is equal to current value int the array assing its index to index variable
if(x == array[i])
{
index = i;
break; //Exit the loop
}
//If no match found assign -1
else
{
index = -1;
}
}
//Return index
return index;
}
}
Comments
Leave a comment