// 1D array that hold 5 scores int scores[5]; // 2D array that holds 4 * 5 scores int scores[4][5]; // 3D array that holds 3 * 4 * 5 scores int scores[3][4][5]; // 4D array that holds 6 * 3 * 4 * 5 scores int scores[6][3][4][5];
int arrayName[ROWS][COLS];
// 2D array that has 4 rows and 5 columns int scores[4][5];
// Place 75 in the first row and first column scores[0][0] = 75; // Place 80 in the last row and last column scores[3][4] = 80;
{}
int scores[4][5] = { { 50, 60, 70, 80, 90 }, // row 0 { 95, 65, 55, 85, 75 }, // row 1 { 80, 90, 70, 50, 60 }, // row 2 { 99, 89, 79, 69, 59 } }; // row 3
for each row { for each column in the row { do something with array[row][col] } } // or for each column { for each row in the column { do something with array[row][col] } }
// Loop through each row for (int r = 0; r < 4; r++) { // Loop through each column in the row for (int c = 0; c < 5; c++) { scores[r][c] = rand() % 101; } }
// Loop through each row for (int r = 0; r < 4; r++) { // Loop through each column in the row for (int c = 0; c < 5; c++) { cout << scores[r][c] << " "; } // Display the next row on the next line cout << endl; }
41 85 72 38 80 69 65 68 96 22 49 67 51 61 63 87 66 24 80 83
// Loop through each row for (int r = 0; r < 4; r++) { // Find the sum of the numbers in this row int total = 0; for (int c = 0; c < 5; c++) { total += scores[r][c]; } // Display the average cout << "Average of row " << r << " is " << total / 5.0 << endl; }
Average of row 0 is 63.2 Average of row 1 is 64 Average of row 2 is 58.2 Average of row 3 is 68
// Loop through each column for (int c = 0; c < 5; c++) { // Find the sum of the numbers in this column int total = 0; for (int r = 0; r < 4; r++) { total += scores[r][c]; } // Display the average cout << "Average of col " << c << " is " << total / 4.0 << endl; }
Average of col 0 is 61.5 Average of col 1 is 70.75 Average of col 2 is 53.75 Average of col 3 is 68.75 Average of col 4 is 62
// Swap the first two numbers on the first row Swap(scores[0][0], scores[0][1]);
const
to write-protect the array parameter
void Test(int nums[][5]) { etc... }
int nums[4][5]; Test(nums);
void DisplayArray(const int nums[][5]) { // Loop through each row for (int r = 0; r < 4; r++) { // Loop through each column in the row for (int c = 0; c < 5; c++) { cout << nums[r][c] << " "; } // Display the next row on the next line cout << endl; } }
double FindAverage(const int nums[], int size) { int total = 0; for (int i = 0; i < size; i++) total += nums[i]; return double(total) / size; }
[]
int scores[4][5]; // Assume this function initializes the array InitializeArray(scores); for (int r = 0; r < 4; r++) { // Pass this row to the function double ave = FindAverage(scores[r], 5); cout << "Average of row " << r << " is " << ave << endl; }