Accessing array elements in C++ involves using array indexing, which allows you to directly access and modify specific elements within an array using their index values. This technique is fundamental in C++ and applies to both statically and dynamically allocated arrays.
In C++, arrays are a collection of elements of the same data type, stored in contiguous memory locations. Each element in an array can be accessed using an index, which starts at 0
for the first element.
The basic syntax for accessing an array element is:
array_name[index]
Here:
array_name
refers to the name of the array.index
specifies the position of the element within the array.Here’s a simple example:
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50}; // Declaring an array of integers
// Accessing array elements
cout << "First element: " << numbers[0] << endl; // Outputs 10
cout << "Second element: " << numbers[1] << endl; // Outputs 20
// Modifying an array element
numbers[2] = 60; // Changing the value of the third element
cout << "Modified third element: " << numbers[2] << endl; // Outputs 60
return 0;
}
0
.for
or while
.#include <iostream>
using namespace std;
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
// Loop to access and display array elements
for (int i = 0; i < 5; i++) {
cout << "Element at index " << i << ": " << numbers[i] << endl;
}
return 0;
}