Mark As Completed Discussion

Accessing Array Elements

When working with arrays, it's important to know how to access individual elements. In C++, array elements can be accessed using the index of the element.

For example, let's consider the following array:

TEXT/X-C++SRC
1int numbers[] = {10, 20, 30, 40, 50};

To access the elements of this array, we use the index value enclosed in square brackets ([]). The index starts from zero for the first element, and it increments by one for each subsequent element. So, to access the first element, we use the index 0. To access the second element, we use the index 1, and so on.

Here's an example of accessing array elements:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  int numbers[] = {10, 20, 30, 40, 50};
6  
7  // Accessing array elements
8  cout << "First element: " << numbers[0] << endl;
9  cout << "Second element: " << numbers[1] << endl;
10  cout << "Third element: " << numbers[2] << endl;
11  cout << "Fourth element: " << numbers[3] << endl;
12  cout << "Fifth element: " << numbers[4] << endl;
13  
14  return 0;
15}

In this example, we declare an array named numbers with 5 elements. We then access and print each element using the index values 0 to 4.

When executing this code, the output will be:

SNIPPET
1First element: 10
2Second element: 20
3Third element: 30
4Fourth element: 40
5Fifth element: 50

Remember, it's crucial to use valid index values within the bounds of the array to avoid accessing elements outside the allocated memory space.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment