Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(Count occurrence of numbers) Write a program that reads the integers between 1

ID: 672832 • Letter: #

Question

(Count occurrence of numbers) Write a program that reads the integers between 1 and 100 and counts the occurrences of each. Assume the input ends with 0. Here is a sample run of the program:

From:'introduction to java programming comprehensive version 10th edition'

7.3 (Count occurrence of numbers) Write a program that reads the integers between 1 and 100 and counts the occurrences of each. Assume the input ends with 0. Here is a sample : run of the program 05432 42 Enter the integers between 1 and 100: 2 5 6 5 4 3 23 43 2 0 Enter 2 occurs 2 times 3 occurs 1 time 4 occurs 1 time 5 occurs 2 times 6 occurs 1 time 23 occurs 1 time 43 occurs 1 time occurs 2 times Note that if a number occurs more than one time, the plural word "times" is used in the output.

Explanation / Answer

CountOccuranceNumbers.java

import java.util.Scanner;

public class CountOccuranceNumbers {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);

        int[] number = new int[100];

        System.out.print("Enter the integers between 1 and 100: ");
        for (int i = 0; i < number.length; i++) {
            int a = input.nextInt();
            number[a] += a;
            if (a == 0)
                break;
        }
        for (int i = 1; i < number.length; i++) {
            if (number[i] != 0) {
                if (number[i] / i > 1)
                    System.out.println(i + " occurs " + number[i] / i + " times");
                else
                    System.out.println(i + " occurs " + number[i] / i + " time");               }
        }
    }
}

Output :

Enter the integers between 1 and 100: 2 5 6 5 4 3 23 43 2 0
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time