// This program will print out an array of arrays // Welcome to 2D arrays! // Declare and create a 3 x 3 two-dimensional array of integer numbers // with the numbers read in from the user. Then loop through the // two-dimensional array, printing out the values in the first row followed // by those in the second row and so on. // Let's extend it to loop through the array to count the number // of even numbers in the 2D array // Week 4: Lecture 7 - 2D Arrays #include #define MAX_ROW 3 #define MAX_COL 3 void print_array(int array[MAX_ROW][MAX_COL]); int count_even(int array[MAX_ROW][MAX_COL]); int main(void) { // Declare an array of arrays that will be able to house user input int array[MAX_ROW][MAX_COL]; // You can also declare and initialise in this way: // int array2[][] = {{1, 2, 3}, {1, 2, 3}, {4, 5, 6}}; // Variable names i and j are perfectly okay here instead of row and col // Will first demonstrate with row and col so you see the way it moves int row = 0; int col = 0; for(row = 0; row < MAX_ROW; row++) { for (col = 0; col < MAX_COL; col++) { printf("Enter a number: "); scanf("%d", &array[row][col]); } } // Call the function to print out the 2D array here: print_array(array); // Call the function to count even numbers: printf("The number of even numbers in the 2D array is %d\n", count_even(array)); return 0; } // Function to print out a 2D Array // INPUT: array // OUTPUT: void // Name: print_array void print_array(int array[MAX_ROW][MAX_COL]) { for(int row = 0; row < MAX_ROW; row++) { for(int col = 0; col < MAX_COL; col++){ printf("%d", array[row][col]); } printf("\n"); } } // Function to count the number of even numbers in 2D array // INPUT: array (2D) // OUTPUT: int (count of the evens) // name: count_even int count_even(int array[MAX_ROW][MAX_COL]) { int count = 0; for(int row = 0; row < MAX_ROW; row++) { for(int col = 0; col < MAX_COL; col++) { if(array[row][col] % 2 == 0) { count++; } } } return count; }