FOR FREE CONTENT

Frequency of Odd and Even in a Matrix

Back to Programming

Description

The even numbers are those numbers that are divisible by 0 and the odd numbers are those numbers that are not divisible by 2. Here the frequency of odd and even elements in the matrix means the number of even and odd elements in the matrix. 

Let the matrix be:

 

Now, each element is checked for even or odd, two extra variables are taken to store the frequency of even and odd.

 

First, the element ‘10’ is divided by 2. Here, the remainder is 0, so, the counter for counting the even numbers will be incremented by 1.

 

Similarly, row-wise the 2nd element will be divided by 2. Here, it is not divisible by 2. Therefore, the counter for counting odd numbers will be incremented by 1.

This process will be continued till the last element of the matrix and after completing this process the frequency of even numbers is 5 and the frequency of odd elements is 4.

Algorithm

INPUT: A matrix 
OUTPUT: The frequency of even and odd numbers

PROCESS:
Step 1: [Taking the inputs]
	Read m, n [The number of rows and columns of the matrix]
	For i=0 to m-1 repeat
		For j=0 to n-1 repeat
			Read a[i][j]
		[End of ‘for’ loop]
	[End of ‘for’ loop]
Step 2: [checking for odd and even numbers]
for i = 0 to m-1 repeat
        		for j = 0 to n-1 repeat
            			if a[i][j] mod 2= 0 then
                			Set e<-e+1
            			else
            				Set o<-o+1
			[End of ‘if’]
		[End of ‘for’ loop]
	[End of ‘for’ loop]
	Print "The number of even elements are: e and The number of odd elements: o”
Step 3: Stop.

Code

TIME COMPLEXITY:

 for (i = 0; i < m; i++)---------------------- O(m)

        for (j = 0; j < n; j++)------------------ O(n)

        {  if (a[i][j]%2== 0)------------------- O(c1)

                e+=1;

            else--------------------------------- O(c2)

                o+=1;

}

The complexity is O(m*n). if the number of rows and columns are same, the complexity is O(n2).

Contributed by