In the provided example, odd numbers are denoted by blue squares, while even numbers are represented by orange circles. To determine the frequencies of odd and even numbers, we can iterate through the matrix and check if each element is divisible by 2. If an element is divisible by 2 (indicating an even number), we increment the count of countEven by 1. Otherwise, if the element is not divisible by 2 (representing an odd number), we increment the count of countOdd by 1.
Algorithm to Find the Frequency of Odd and Even Numbers in a Matrix
-
- STEP 1: START
- STEP 2: DEFINE rows, cols
- STEP 3: SET countOdd = 0, countEven =0
- STEP 4:INITIALIZE matrix a[][] ={{4,1,3},{3, 5, 7}, {8, 2, 6}}
- STEP 5: rows = a.length
- STEP 6: cols = a[0].length
- STEP 7: REPEAT STEP 8 to STEP 9 UNTIL i<rows for(i=0; i<rows; i++)
- STEP 8: REPEAT STEP 9 UNTIL j<cols
- STEP 9: if(a[i][j]%2 ==0)
countEven++
else
countOdd++ - STEP 10: PRINT “Frequency of odd numbers ” by assigning countOdd.
- STEP 11: PRINT “Frequency of even numbers ” by assigning countEven
- STEP 12: END
Java Program to Find the Frequency of Odd and Even Numbers in a Matrix
public class OddEven { public static void main(String[] args) { int rows, cols, countOdd = 0, countEven = 0; //Initialize matrix a int a[][] = { {4, 1, 3}, {3, 5, 7}, {8, 2, 6} }; //Calculates number of rows and columns present in given matrix rows = a.length; cols = a[0].length; //Counts the number of even elements and odd elements for(int i = 0; i < rows; i++){ for(int j = 0; j < cols; j++){ if(a[i][j] % 2 == 0) countEven++; else countOdd++; } } System.out.println("Frequency of odd numbers: " + countOdd); System.out.println("Frequency of even numbers: " + countEven); } }
Output:
Frequency of odd numbers: 5 Frequency of even numbers: 4
In conclusion, the Java program presented enables the determination of the frequency of odd and even numbers within a matrix. By looping through the matrix and checking the divisibility of each element by 2, we can increment separate counters for odd and even numbers. Follow tutorials.freshersnow.com to learn more.