矩阵中偶数和奇数频率的Java程序
给定一个 m*n 阶矩阵,那么任务是找到矩阵中偶数和奇数的频率
例子:
Input : m = 3, n = 3
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
Output : Frequency of odd number = 5
Frequency of even number = 4
Input : m = 3, n = 3
{ 10, 11, 12 },
{ 13, 14, 15 },
{ 16, 17, 18 }
Output : Frequency of odd number = 4
Frequency of even number = 5
Java
// Java Program to Find the frequency
// of even and odd numbers in a matrix
class GFG {
static final int MAX = 100;
// function for calculating frequency
static void freq(int ar[][], int m, int n) {
int even = 0, odd = 0;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
// modulo by 2 to check
// even and odd
if ((ar[i][j] % 2) == 0)
++even;
else
++odd;
}
}
// print Frequency of numbers
System.out.print(" Frequency of odd number =" +
odd + "
");
System.out.print(" Frequency of even number = " +
even + "
");
}
// Driver code
public static void main(String[] args) {
int m = 3, n = 3;
int array[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
freq(array, m, n);
}
}
// This code is contributed by Anant Agarwal.
输出:
Frequency of odd number = 5
Frequency of even number = 4
有关更多详细信息,请参阅有关矩阵中偶数和奇数频率的完整文章!