blog
blog copied to clipboard
C++ Two-Dimensional Arrays
Concept: A two-dimensional array is like several identical arrays put together. It is useful for storing multiple sets of data.
double array[Rows][Columns];
// Assigns the value 99.5 to the element at
// row#2 column#1 of the scores array:
scores[1][0] = 99.5;
1. Two-dimensional array initialization
#include <iostream>
using namespace std;
int main() {
const int ROWS = 3;
const int COLUMNS = 4;
// The extra braces that enclose each row's initialization list
// is optional.
// int num_ppl[ROWS][COLUMNS] = {
// 4, 5, 2, 3, 0, 0, 5, 5, 5, 4, 2, 0
// };
int num_ppl[ROWS][COLUMNS] = {{4, 5, 2, 3},
{0, 0, 5, 5},
{5, 4, 2, 0}
};
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLUMNS; j++) {
cout << num_ppl[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output:
4 5 2 3
0 0 5 5
5 4 2 0
2. Passing Two-Dimensional Arrays to Functions
When a two-dimensional array is passed to a function, the parameter type must contain a size declarator for the number of columns.
Here is the header for the function print_2D_array
below:
void print_2D_array(int arr[][COLUMNS], int rows)
#include <iostream>
using namespace std;
const int COLUMNS = 4;
// Function prototype:
void print_2D_array(int[][COLUMNS], int);
int main() {
const int ROWS = 3;
int num_ppl[ROWS][COLUMNS] = {{1, 2, 2, 3},
{0, 0, 5, 5},
{5, 4, 2, 0}
};
print_2D_array(num_ppl, ROWS);
return 0;
}
void print_2D_array(int arr[][COLUMNS], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < COLUMNS; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
Output:
1 2 2 3
0 0 5 5
5 4 2 0