Write a subprogram that is given an array of integers and a given integer to search for. Scan the array for matches with the given integer and create an array of the indexes with the matching entries. To store the indexes, start with an array of the same size, but, after finishing the scan, allocate an array of just the right size, copy the contents, and return the (potentially) smaller array.

Respuesta :

Answer:

public class Main

{

public static void main(String[] args) {

    int[] numbers = {28, 7, 92, 100, 0, 7, 300, 2873};

    int target = 7;

    int count = 0;

   

    int[] matchedIndexes = new int[numbers.length];

   

    for(int i = 0; i<numbers.length; i++){

        if (numbers[i] == target){

            matchedIndexes[count] = i;

            count++;

        }

    }

   

    int[] indexes = new int[count];

   

    for(int i = 0; i<count; i++){

       indexes[i] = matchedIndexes[i];

    }

   

    for(int i = 0; i<count; i++){

     System.out.print(indexes[i] + " ");

    }

}

}

Explanation:

Initialize the numbers array, target value and count

Create a new array called matchedIndexes with the size of the numbers array

Create a for loop that iterates through the numbers array and checks if the target is in the numbers array. If it is, put the index of the number in to the matchedIndexes array and increment the count by 1.

Create another array named indexes with size of count

Create a for loop that copies the values from matchedIndexes to indexes

Print the values in the indexes