Ask Question
20 August, 18:50

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}

+2
Answers (1)
  1. 20 August, 20:35
    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?
Find 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 you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers