Ask Question
19 March, 10:56

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.

+2
Answers (1)
  1. 19 March, 11:28
    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?
Find 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 and Technology 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