How to get the first element of an array in C++
In this tutorial, we are going to learn about how to get the first element of an array in C++.
Consider, we have the following array.
array<int,4> nums {20, 30, 40, 50};
Now, we want to get the first element 20
from the above array.
To get the first element (20) from the array, we can use the subscript operator [ ]
by passing an index 0
.
In C++ arrays are zero-indexed, so the first element index of an array is
0
.
Here is an example:
#include <iostream>
#include <array>
using namespace std;
int main()
{
array<int,4> nums {20, 30, 40, 50};
int firstElement = nums[0];
cout<<"First element is: "<<firstElement<<endl;
return 0;
}
Output:
20