/*
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
*/
func countOddEven(_ matrix: [[Int]]) -> (odd: Int, even: Int) {
// Automatically compute matrix dimensions inside the function
let rows: Int = matrix.count
let cols: Int = matrix[0].count
var odd: Int = 0
var even: Int = 0
for i in 0..<rows {
for j in 0..<cols {
// Check if the number is even or odd
if matrix[i][j] % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (odd, even)
}
func main() {
let matrix: [[Int]] = [
[1, 0, 2, 5],
[3, 5, 6, 9],
[7, 4, 1, 8]
]
// Call the function (rows and cols are now computed inside)
let result = countOddEven(matrix)
let oddCount = result.odd
let evenCount = result.even
// Display the result
print("The frequency of odd numbers = \(oddCount)")
print("The frequency of even numbers = \(evenCount)")
}
main()
/*
run:
The frequency of odd numbers = 7
The frequency of even numbers = 5
*/