How to Declare an Array in C++?
Last Updated : 18 Mar, 2024
Improve
In C++, an array is a collection of similar data types in which elements are stored in contiguous memory locations. In this article, we will learn how to declare an array in C++.
Declaring an Array in C++
In C++, we can declare an array by specifying the type of its elements, followed by the name of the array and the size in square brackets.
Syntax to Declare an Array in C++
Datatype arrayName[arraySize];
To directly initialize the elements in the array we can use the below syntax:
Datatype ArrayName [ArraySize] = {element1, element2, ....}
If we want to declare an array with more dimensions, we can just keep adding the dimensions after the first dimensions with their size inside the array subscript operator.
C++ Program to Declare an Array
The below program illustrates how we can declare an array in C++.
// C++ Program to show how to declare an array
#include <iostream>
using namespace std;
int main()
{
// Declaring an array of 4 elements
int arr[4] = { 1, 2, 3, 4 };
// Print the elements of the array
cout << "Array Elements: ";
for (int i = 0; i < 4; i++)
cout << arr[i] << " ";
return 0;
}
Output
Array Elements: 1 2 3 4
Time Complexity: O(1), constant time required only for declaration.
Auxiliary Space: O(N)