87.7k views
3 votes
Please help ASAP! This is Java and is from a beginner's comp sci class!

Assignment Details;
Write a program that creates a basic "number histogram".
First, create an array with 25 elements, like this (use this variable name):
int[] data = new int[25];
Using a for loop, change the value at each index in data to a randomly generated integer from 0 - 9 . The data array should contain different values every time your program runs.
Declare and initialize a second array that will represent the histogram:
int[] histogram = new int[10];
histogram will store the number of times each number (0-9) occurs in data. Your solution should ideally NOT use ten if statements inside the loop (e.g. if (data[i] == 0), if (data[i] == 1), ...) – you need to think with arrays! Given a data array containing the values: [9, 8, 2, 8, 1, 1, 8, 5, 0, 4, 5, 5, 0, 5, 8, 8, 1, 4, 5, 9, 7, 8, 2, 5, 0]
your program would output the following (it should change each time it runs):
0 - occurred 3 time(s)
1 - occurred 3 time(s)
2 - occurred 2 time(s)
3 - occurred 0 time(s)
4 - occurred 2 time(s)
5 - occurred 6 time(s)
6 - occurred 0 time(s)
7 - occurred 1 time(s)
8 - occurred 6 time(s)
9 - occurred 2 time(s)

1 Answer

6 votes

Answer:

import java.util.Random;

public class NumberHistogram {

public static void main(String[] args) {

int[] data = new int[25];

Random rand = new Random();

// Fill data array with random numbers from 0-9

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

data[i] = rand.nextInt(10);

}

int[] histogram = new int[10];

// Count occurrences of each number in data and store in histogram array

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

histogram[data[i]]++;

}

// Print histogram

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

System.out.println(i + " - occurred " + histogram[i] + " time(s)");

}

}

}

Step-by-step explanation:

This program uses a for loop to fill the data array with random integers between 0 and 9, and then uses another for loop to count the occurrences of each number in data and store the counts in the histogram array. Finally, the program uses a third for loop to print out the histogram.

The test variable in this program is the randomly generated integers in the data array. The outcome variable is the histogram of the occurrences of each number in the data array. The control variable is the fixed range of integers from 0 to 9.

Note that this solution uses an array to avoid using ten if statements inside the loop. Instead, it uses the current element of the data array as an index into the histogram array and increments the corresponding element. This way, the counts for each number are automatically tallied without needing to check each possible value.

User Jprism
by
7.7k points