Ask Question
9 October, 16:15

Write a program that populates an array with 20 random integers between 1 - 100. The program must traverse through the array and determine how many times each integer was generated. Use a second array of size 101 to keep track of the number of times each integer was generated. Initialize each item in the second array to 0. For each item in the first array, use it as the index into the second array and increment the contents found in the second array at the corresponding index. Note: for this problem we are willing to trade memory efficiency (the second array is mostly unused) for time efficiency. We know indexing into an array is very efficient.

+3
Answers (1)
  1. 9 October, 16:24
    0
    import java. util. Arrays; import java. util. Random; public class Main { public static void main (String [] args) { int a [] = new int[20]; Random rand = new Random (); for (int i=0; i < a. length; i++) { a[i] = rand. nextInt (100) + 1; } int b [] = new int [101]; for (int i = 0; i < b. length; i++) { b[i] = 0; } for (int j=0; j < a. length; j++) { int index = a[j]; b[index]++; } System. out. println (Arrays. toString (b)); } }

    Explanation:

    The solution code is written in Java. Firstly, create an integer type array with size 20 (Line 8). Next create a random object and use this object method nextInt to generate 20 random integer between 1 - 100 within a for loop (Line 15 - 17).

    Create a second integer array with size 101 (Line 17).

    Create a for loop to traverse through the second array and set all the items to zero (Line 19 - 21).

    Create another for loop to traverse through the first array and this time get the value of each item and set it as an index (Line 25) and use the index to address the target item of second array. Increment the target item in second array be one (Line 26).

    After completion the loop, print out the second array (Line 29)
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Write a program that populates an array with 20 random integers between 1 - 100. The program must traverse through the array and determine ...” in 📙 Computers & Technology 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