5️⃣

7.5 Accessing Array Elements

Accessing array elements is simple now that we have gone over how to iterate through arrays. If you want to retrieve a certain element, you would type the name of the array, open a pair of square brackets, and type the index value of the element you would like to retrieve inside of the square brackets. Let’s look at an example:
int nums[] = {1, 2, 3, 4, 5}; int firstElement = nums[0];
In the above code, the first line just declares and initializes the array called nums. In the second line, we’re trying to store the first element of the array into a variable of type int called firstElement. We can reference the first element of the array by using its index value. Remember the index value of the first element is always 0, so knowing this information, we can successfully set the variable firstElement equal to the first element of the array, or 1. In this manner, you can access any element of an array with its index value.

Previous Section

4️⃣
7.4 Iterating Through Arrays
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.