212k views
2 votes
Design and implement an application that reads an arbitrary number of integers that are in the range 0 to 50 inclusive and counts how many occurrences of each are entered. After all input has been processed, print all of the values (with the number of occurrences) that were entered one or more times. The output should be one frequency count per line with the following format: 3 occurrences of 2 7 occurrences of 5

User Stvnrlly
by
5.3k points

1 Answer

2 votes

Answer:

  1. import java.util.Scanner;
  2. public class Main {
  3. public static void main(String[] args)
  4. {
  5. int numArr [] = new int[51];
  6. int num;
  7. Scanner input = new Scanner(System.in);
  8. do{
  9. System.out.print("Input number between 0 - 50: ");
  10. num = input.nextInt();
  11. if(num >= 0 && num <= 50){
  12. numArr[num]++;
  13. }
  14. }while(num != -1);
  15. for(int i=0; i < numArr.length; i++){
  16. if(numArr[i] > 0){
  17. System.out.println(numArr[i] + " occurrences of " + i);
  18. }
  19. }
  20. }
  21. }

Step-by-step explanation:

The solution code is written in Java.

Firstly, create a numArr array with 51 elements (Line 6).

Next, use do while loop to repeatedly prompt user for an input number between 0 - 50. If num is between 0 - 50, use the input number as index to increment that particular element of array by one (Line 10 - 15).

At last, create another for-loop to traverse through the numArr array and print all the elements with value at least one (Line 18 - 21).

User Aung Myat Hein
by
6.1k points