Answer to Question #184703 in Java | JSP | JSF for salma wael

Question #184703

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


1
Expert's answer
2021-04-24T06:11:23-0400
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;
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS