Ask Question
16 January, 14:13

Write a Java method, smallestIndex, that takes as its parameters an int array, and returns the index of the (last occurrence of the) smallest element in the array. Write a program to test your method. Use the following array values: {10 5 15 12 3 16 25 42 3 30}

+5
Answers (1)
  1. 16 January, 14:48
    0
    public class Main { public static void main (String[] args) { int testArray [] = {10,5,15,12,3,16,25,42,3,30}; int minIndex = smallestIndex (testArray); System. out. println (minIndex); } public static int smallestIndex (int [] arr) { int smallest = arr[0]; int result=0; for (int i=1; i < arr. length; i++) { if (arr[i] < = smallest) { smallest = arr[i]; result = i; } } return result; } }

    Explanation:

    Firstly, we define a method smallestIndex that take one integer array (Line 9).

    We create a variable smallest and another variable result to hold the value of smallest number in the array and its index position. We tentatively set the first element of the array as smallest (Line 10-11).

    Next, create a for loop to traverse through the array elements starting with index-1 and then check if the current element is smaller or equal to the current smallest value. If so set the current element to smallest variable and set the current index to result variable (Line 14-16).

    After the loop return the result (Line 19).

    In the main program, we test the method using the sample array and print out the result (Line 4-6). We shall get 8 which is the index position where the last occurrence of the smallest element found in the array.
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Write a Java method, smallestIndex, that takes as its parameters an int array, and returns the index of the (last occurrence of the) ...” in 📙 Engineering if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers