Access Elements in C++ Array

To access elements in a C++ array, follow these steps:

  1. Declare the Array: Create an array and initialize it with elements.

cpp int myArray[5] = {10, 20, 30, 40, 50};

  1. Access an Element by Index: Use the index of the element within square brackets to access the value at that index.

cpp int thirdElement = myArray[2]; // Accessing the third element (index 2)

  1. Modify an Element: Use the index to modify the value of an element in the array.

cpp myArray[1] = 100; // Modifying the value of the second element (index 1)

  1. Iterate Through the Array: Use a loop to iterate through the array and access each element.

cpp for (int i = 0; i < 5; i++) { cout << myArray[i] << " "; // Output each element separated by a space }

  1. Use Pointer Arithmetic: You can also use pointer arithmetic to access array elements.

cpp int fifthElement = *(myArray + 4); // Accessing the fifth element using pointer arithmetic

These steps will allow you to effectively access and manipulate elements within a C++ array.