Array:
An array in C++ is a group of identically typed variables that may be accessed using both a common name and an index. An array's variables are kept in contiguous memory locations, enabling quick access to each variable's constituent elements.
In C++, arrays are declared by stating the data type of the array's elements, the array name, the number of elements, and square brackets around the number.
In C++, arrays are declared by stating the data type of the array's elements, the array name, the number of elements, and square brackets around the number.
Syntax:
Data_type Array_Name [size];
Type of array:
- One-dimensional
- Two-dimensional
- Multidimensional
One-dimensional:
A one-dimensional array is one in which the components are arranged in a single row or column. It is the most basic kind of array and is used to store a collection of identically typed data components.
Example:
#include <iostream>
using namespace std;
int main() {
const int SIZE = 5;
int myArray[SIZE] = {1, 2, 3, 4, 5};
// Print the elements of the array
for (int i = 0; i < SIZE; i++) {
cout << myArray[i] << " ";
}
cout << endl;
return 0;
}
Output:
12345
Two-dimensional:
In C++, a two-dimensional array is an array of arrays in which each element is an array. A table or matrix are two other names for it.
Syntax:
data_type array_name[row_size][column_size];
Example:
#include <iostream>
using namespace std;
int main() {
const int ROWS = 3;
const int COLS = 4;
int myArray[ROWS][COLS] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Print the elements of the array
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
cout << myArray[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output:
1 2 3 4
5 6 7 8
9 10 11 12
Multidimensional arrays:
A one-dimensional array is one in which the components are arranged in a single row or column. It is the most basic kind of array and is used to store a collection of identically typed data components.
Syntax:
data_type array_name[dim1_size][dim2_size]...[dimn_size];
Example:
#include <iostream>
using namespace std;
int main() {
const int ROWS = 2;
const int COLS = 3;
const int DEPTH = 4;
int myArray[ROWS][COLS][DEPTH] = {
{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}},
{{13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24}}
};
// Print the elements of the array
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
for (int k = 0; k < DEPTH; k++) {
cout << myArray[i][j][k] << " ";
}
cout << endl;
}
cout << endl;
}
return 0;
}
Output:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
21 22 23 24