224k views
5 votes
Please write a Java program.

Given an array of integers containing values in the range 1 to 6, inclusive, return an array of size 6 containing a count of the number of times each of the six values occur. For example, in the array {3, 1, 1, 2, 4, 4, 4, 6} the number 1 occurs 2 times, the number 2 occurs 1 time, the number 3 occurs 1 time, the number 4 occurs 3 times, the number 5 occurs 0 times, and the number 6 occurs 1 time.
SUGGESTION: This can be solved with a single "for each" loop and no if statements.

User VidasV
by
4.4k points

1 Answer

4 votes

Answer:

public class Main

{

public static void main(String[] args) {

int[] arr = {3, 1, 1, 2, 4, 4, 4, 6};

int[] o = countOccurance(arr);

for (int x: o)

System.out.print(x + " ");

}

public static int[] countOccurance(int[] arr){

int[] occ = new int[6];

for (int x: arr)

occ[x-1]++;

return occ;

}

}

Step-by-step explanation:

Create a function called countOccurance that takes one parameter, an array

Inside the function, initialize an array, occ, to hold the occurance counts

Create a for each loop to iterate the array, and increment the occurance of the numbers

When the loop is done, return the occ array

Inside the main, initialize an array

Call the function countOccurance and set it to a new array, o

Print the elements of the o to see the number of occurances of the numbers

User Amin Keshavarzian
by
4.3k points