Google News
logo
Java Program to find the frequency of Odd & Even Numbers in the Given Matrix
In the following examples of Java program to find the frequency of odd and even numbers in a given matrix :
Program :
public class FrequencyOfOddEvenNumbers {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        findFrequency(matrix);
    }

    public static void findFrequency(int[][] matrix) {
        int oddCount = 0;
        int evenCount = 0;
        for (int[] row : matrix) {
            for (int num : row) {
                if (num % 2 == 0) {
                    evenCount++;
                } else {
                    oddCount++;
                }
            }
        }
        System.out.println("Frequency of even numbers: " + evenCount);
        System.out.println("Frequency of odd numbers: " + oddCount);
    }
}
Output :
Frequency of even numbers: 4
Frequency of odd numbers: 5
In this program, we have a matrix matrix represented as a two-dimensional array. We define a method findFrequency that takes the matrix as input and finds the frequency of odd and even numbers in the matrix.

We initialize two variables oddCount and evenCount to zero to keep track of the frequency of odd and even numbers in the matrix. We then use two nested loops to iterate over the elements of the matrix. The outer loop iterates over the rows, and the inner loop iterates over the columns.

For each number in the matrix, we check whether it is even or odd by using the modulo operator. If the number is even, we increment the evenCount variable. Otherwise, we increment the oddCount variable.