CodeBlanks Logo Icon CodeBlanks

Array access

Learn to access and modify array elements by index.

Array access

To access array elements you write the index inside square brackets. nums[0] gives the first element, nums[2] the third. Because indices start at zero, nums[i] actually represents the (i+1)th element.

The same syntax lets you change an element: nums[1] = 99; sets the second element to 99. Using an index beyond the array size (such as nums[10] on a five-element array) causes undefined behavior, so keep the index under control.

Modifying arrays

You can change array contents by assigning to its elements. Writing nums[1] = 99; changes only that element; others stay the same. This lets you update the array from a single point.

You can rewrite all elements by assigning in a loop. For example for (int i = 0; i < 5; i++) nums[i] = 0; zeroes every element. Because the array size is fixed, memory management is automatic; you do not need new or delete.

Practice Change the second element and print it

The nums array is set to {10, 20, 30, 40, 50}. Change the second element with nums[1] = 99; and print it with std::cout << nums[1];. The output must be 99.

Starter code

main.cpp
#include <iostream>

int main() {
    int nums[5] = {10, 20, 30, 40, 50};
    // Change the second element to 99 and print it
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    int nums[5] = {10, 20, 30, 40, 50};
    nums[1] = 99;
    std::cout << nums[1] << std::endl;
    return 0;
}

Expected output

99

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the third element

Question
int nums[5] = {10, 20, 30, 40, 50};
std::cout << ____;
Answer
int nums[5] = {10, 20, 30, 40, 50};
std::cout << nums[2];

Explanation: nums[2] gives the third element, 30.

2 Match each access pattern to its meaning

Term Meaning
nums[0] First element
nums[1] Second element
nums[4] Last element (5 elements)
nums[i] i-th index

3 What does nums[3] = 99; do?

main.cpp
int nums[5] = {10,20,30,40,50};
nums[3] = 99;
  • Reads the third element
  • Divides the array by 3
  • Sets the fourth element to 99 Correct answer
  • Sets the total to 99

Explanation: nums[3] = 99; sets the fourth element to 99 (index 3).

All lessons in Beginner