How to calculates the frequency of odd and even numbers in the given matrix with C#

1 Answer

0 votes
using System;

class Program
{
    /*
        Function: countOddEven
        Purpose:  Counts how many odd and even numbers exist in the matrix.
        Parameters:
            - matrix: the 2D array
            - rows:   number of rows in the matrix   (computed inside the function)
            - cols:   number of columns in the matrix (computed inside the function)
            - odd:    variable to store odd count
            - even:   variable to store even count
    */
    static (int odd, int even) CountOddEven(int[,] matrix)
    {
        // Automatically compute matrix dimensions inside the function
        int rows = matrix.GetLength(0);
        int cols = matrix.GetLength(1);

        int odd = 0;
        int even = 0;

        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                // Check if the number is even or odd
                if (matrix[i, j] % 2 == 0)
                    even++;
                else
                    odd++;
            }
        }

        return (odd, even);
    }

    static void Main()
    {
        int[,] matrix =
        {
            {1, 0, 2, 5},
            {3, 5, 6, 9},
            {7, 4, 1, 8}
        };

        // Call the function (rows and cols are now computed inside)
        var result = CountOddEven(matrix);
        int oddCount = result.odd;
        int evenCount = result.even;

        // Display the result
        Console.WriteLine("The frequency of odd numbers = " + oddCount);
        Console.WriteLine("The frequency of even numbers = " + evenCount);
    }
}


/*
run:

The frequency of odd numbers = 7
The frequency of even numbers = 5

*/

 



answered Aug 29, 2021 by avibootz
edited 4 days ago by avibootz

Related questions

...