Exercise #4.1 Integer Frequency

Write a Java function/static method getFrequency(int[] input, int num) that takes as parameter an array of integers input and an integer num and returns the frequency of appearances of num in the array input.

For example, if input = [1, 2, 1] and num = 1, the function should return 2. And if num = 2, the function should return 1.

For example:

Test

Result

int[] input = {1, 2, 1};
System.out.println(getFrequency(input, 1));

2

int[] input = {1, 2, 1};
System.out.println(getFrequency(input, 2));

1

Ans:

public class IntegerFrequency {
    public static void main(String[] args) {
        int[] input = {1, 2, 1};
        System.out.println(getFrequency(input, 2));
    }

    public static int getFrequency(int[] input, int num) {
        int count = 0;
        for (int j : input) if (j == num) count++; //Simplified For-Each Loop
        return count;
    }
}

For-Each Loop Syntax

The syntax of the Java for-each loop is:

for(dataType item : array) {
    ...
}

Here,

  • array - an array or a collection

  • item - each item of array/collection is assigned to this variable

  • dataType - the data type of the array/collection