In: Computer Science
Write a code to initialize a 2D array with random integers (not has to be different). Write a function to count the number of cells that contain an even number within the 2D array.
C++
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; #define ROWS 3 #define COLUMNS 4 int count_evens(int arr[ROWS][COLUMNS]) { int count = 0; for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLUMNS; ++j) { if (arr[i][j] % 2 == 0) { ++count; } } } return count; } int main() { srand(time(NULL)); // create and populate a 2d array with random data int arr[ROWS][COLUMNS]; for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLUMNS; ++j) { arr[i][j] = rand() % 100; } } // print array cout << "2D array is" << endl; for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLUMNS; ++j) { cout << arr[i][j] << " "; } cout << endl; } // print number of evens cout << "Number of even numbers in array is " << count_evens(arr) << endl; return 0; }