JAVA SP T


Lets dive into snapshot of my programs!💻

8.Program to find the frequency of odd & even numbers in the given matrix

💡Code:

  import java.util.Scanner;

              public class FrequencyOddEven7078 {
                  public static void main(String[] args) {
                      Scanner scanner = new Scanner(System.in);
              
                      // Get the dimensions of the matrix from the user
                      System.out.print("Enter the number of rows: ");
                      int rows = scanner.nextInt();
                      System.out.print("Enter the number of columns: ");
                      int columns = scanner.nextInt();
              
                      // Create the matrix
                      int[][] matrix = new int[rows][columns];
                      System.out.println("Enter elements for the matrix:");
                      inputMatrix(matrix, scanner);
              
                      // Find the frequency of odd and even numbers
                      int oddFrequency = 0;
                      int evenFrequency = 0;
              
                      for (int[] row : matrix) {
                          for (int element : row) {
                              if (element % 2 == 0) {
                                  evenFrequency++;
                              } else {
                                  oddFrequency++;
                              }
                          }
                      }
              
                      // Display the result
                      System.out.println("Frequency of Odd Numbers: " + oddFrequency);
                      System.out.println("Frequency of Even Numbers: " + evenFrequency);
              
                      // Close the scanner
                      scanner.close();
                  }
              
                  // Function to input elements into a matrix
                  private static void inputMatrix(int[][] matrix, Scanner scanner) {
                      for (int i = 0; i < matrix.length; i++) {
                          for (int j = 0; j < matrix[0].length; j++) {
                              System.out.print("Enter element at position [" + (i + 1) + "][" + (j + 1) + "]: ");
                              matrix[i][j] = scanner.nextInt();
                          }
                      }
                  }
              }
               

📸Output :

output