How to calculates the frequency of odd and even numbers in the given matrix with VB.NET

1 Answer

0 votes
Imports System

Module 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
    '
    Function CountOddEven(matrix As Integer(,)) As (odd As Integer, even As Integer)

        ' Automatically compute matrix dimensions inside the function
        Dim rows As Integer = matrix.GetLength(0)
        Dim cols As Integer = matrix.GetLength(1)

        Dim odd As Integer = 0
        Dim even As Integer = 0

        For i As Integer = 0 To rows - 1
            For j As Integer = 0 To cols - 1

                ' Check if the number is even or odd
                If matrix(i, j) Mod 2 = 0 Then
                    even += 1
                Else
                    odd += 1
                End If
            Next
        Next

        Return (odd, even)
    End Function

    Sub Main()

        Dim matrix As Integer(,) = {
            {1, 0, 2, 5},
            {3, 5, 6, 9},
            {7, 4, 1, 8}
        }

        ' Call the function (rows and cols are now computed inside)
        Dim result = CountOddEven(matrix)
        Dim oddCount As Integer = result.odd
        Dim evenCount As Integer = result.even

        ' Display the result
        Console.WriteLine("The frequency of odd numbers = " & oddCount)
        Console.WriteLine("The frequency of even numbers = " & evenCount)

    End Sub

End Module


'
'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

...