Accessing an Element of an Array in C++
Elements of an array can be accessed by specifying the name of the array, then the index of the element enclosed in the array subscript operator []. For example, arr[i].
Example 1: The C++ Program to Illustrate How to Access Array Elements
// C++ Program to Illustrate How to Access Array Elements
#include <iostream>
using namespace std;
int main()
{
int arr[3];
// Inserting elements in an array
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
// Accessing and printing elements of the array
cout << "arr[0]: " << arr[0] << endl;
cout << "arr[1]: " << arr[1] << endl;
cout << "arr[2]: " << arr[2] << endl;
return 0;
}
Output
arr[0]: 10 arr[1]: 20 arr[2]: 30
C++ Arrays
In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location.
For example, if we have to store the marks of 4 or 5 students then we can easily store them by creating 5 different variables but what if we want to store marks of 100 students or say 500 students then it becomes very challenging to create that numbers of variable and manage them. Now, arrays come into the picture that can do it easily by just creating an array of the required size.