In C++, an array is a collection of variables of the same data type. Each element in the array is identified by an index or a subscript. The general syntax for declaring and initializing an array in C++ is as follows:
datatype arrayname [arraysize] = {initializer1, initializer2, ..., initializerN};
where datatype
is the type of data that the array will hold (e.g. int, float, char), arrayname
is the name of the array, arraysize
is the number of elements in the array, and initializer1
, initializer2
, …, initializerN
are the values used to initialize each element of the array.
Here is an example of how to declare and initialize an array of integers in C++:
int numbers[5] = {1, 2, 3, 4, 5};
This creates an array called numbers
with 5 elements, where each element is initialized with the corresponding value. The first element is 1, the second element is 2, and so on.
To access an element in the array, you use the array name followed by the index enclosed in square brackets. For example, to access the third element in the numbers
array, you would use the following syntax:
int x = numbers[2]; // sets x to 3
It’s important to note that array indices start at 0, so the first element in the array is accessed using index 0, the second element is accessed using index 1, and so on.
You can also initialize an array with default values. Here is an example of how to declare and initialize an array of integers with default values:
int numbers[5] = {0}; // initializes all elements to 0
In this example, the first element of the numbers
array is initialized to 0, and the remaining elements are also initialized to 0 because they were not specified.
You can also create multi-dimensional arrays by using multiple sets of square brackets. Here is an example of how to declare and initialize a 2-dimensional array of integers:
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
In this example, matrix
is a 3×3 array of integers. The first set of curly braces specifies the values for the first row, the second set of curly braces specifies the values for the second row, and so on. To access an element in a multi-dimensional array, you use the same syntax as for a one-dimensional array, but with multiple indices. For example, to access the element in the second row and third column of the matrix
array, you would use the following syntax:
int x = matrix[1][2];