Multidimensional arrays are created by specifying two or more pairs of square brackets in the declaration. Multi-dimensional arrays are created as arrays of arrays. The initialization takes place in the same way as one-dimensional arrays by specifying the number of elements per dimension. Multi-dimensional arrays can be accessed by specifying all required indices, each in their own square brackets. Even with multi-dimensional arrays, a literal initialization can be achieved by nesting the initialization sequences.
type array_name[size1][size2];
int matrix[3][4];
matrix
with 3 rows and 4 columns.type array_name[size1][size2] = {{row1_values}, {row2_values}, ..., {rowN_values}};
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
#include <iostream>
using namespace std;
int main() {
// Single-dimensional array
int numbers[5] = {1, 2, 3, 4, 5};
// Accessing and printing elements
for (int i = 0; i < 5; i++) {
cout << "Element at index " << i << ": " << numbers[i] << endl;
}
// Multi-dimensional array
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Accessing and printing elements
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << "Element at [" << i << "][" << j << "]: " << matrix[i][j] << endl;
}
}
return 0;
}
#include <iostream>
std::cout
for console output.using namespace std;
std::
.int main() {
main
function is the starting point of the program.int numbers[5] = {1, 2, 3, 4, 5};
numbers
with 5 elements and initializes it with the values {1, 2, 3, 4, 5}
.for (int i = 0; i < 5; i++) {
cout << "Element at index " << i << ": " << numbers[i] << endl;
}
int i = 0
initializes the loop counter i
to 0.i < 5
runs the loop as long as i
is less than 5.i++
increments i
by 1 after each iteration.cout << "Element at index " << i << ": " << numbers[i] << endl;
prints the value of numbers[i]
at each index i
.int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
matrix
with 3 rows and 4 columns, initializing it with the values provided.for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << "Element at [" << i << "][" << j << "]: " << matrix[i][j] << endl;
}
}
int i = 0
initializes the outer loop counter i
to 0.i < 3
runs the outer loop as long as i
is less than 3.i++
increments i
by 1 after each iteration.int j = 0
initializes the inner loop counter j
to 0