Skip to content
Related Articles

Related Articles

C++ Program for Frequencies of even and odd numbers in a matrix

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 24 Jun, 2022

Given a matrix of order m*n then the task is to find the frequency of even and odd numbers in the matrix 
Examples: 

Input : m = 3, n = 3
        { 1, 2, 3 }, 
        { 4, 5, 6 }, 
        { 7, 8, 9 }
Output : Frequency of odd number =  5 
         Frequency of even number = 4


Input :   m = 3, n = 3
         { 10, 11, 12 },
         { 13, 14, 15 },
         { 16, 17, 18 }
Output : Frequency of odd number  =  4 
         Frequency of even number  = 5
 

CPP




// C++ Program to Find the frequency
// of even and odd numbers in a matrix
#include <bits/stdc++.h>
using namespace std;
 
#define MAX 100
 
// function for calculating frequency
void freq(int ar[][MAX], int m, int n)
{
    int even = 0, odd = 0;
 
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            // modulo by 2 to check
            // even and odd
            if ((ar[i][j] % 2) == 0)
                ++even;
            else
                ++odd;
        }
    }
 
    // print Frequency of numbers
    cout << "Frequency of odd number = " << odd << endl;
    cout << "Frequency of even number = " << even << endl;
}
 
// Driver code
int main()
{
    int m = 3, n = 3;
 
    int array[][MAX]
        = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
    freq(array, m, n);
    return 0;
}


Output

Frequency of odd number = 5
Frequency of even number = 4

Time Complexity: O(m*n), Where m is the number of rows and n is the number of columns in the given matrix.
Auxiliary Space: O(1)

Please refer complete article on Frequencies of even and odd numbers in a matrix for more details!

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!