CodeBlanks Logo Icon CodeBlanks

Arrays and loops

Learn to iterate over arrays with for.

Arrays and loops

To process every element of an array you use a for loop. The most common pattern is for (int i = 0; i < N; i++) ... nums[i] .... Here N is the array size.

In this pattern i starts at 0, runs while below N, and on each iteration nums[i] takes one element. C-style arrays keep the size separately, so you write N by hand. With std::array you can fetch it dynamically via nums.size().

Range-based for with arrays

Besides the classic for, range-based for also works with C-style arrays: for (int x : nums) std::cout << x;. This form is shorter and safer when you do not need the index.

However, when you need the index (for example, to print the element number), the classic for is required. With std::array both range-based for and classic for via nums.size() work; both are safe. Picking the right tool for the right place improves readability.

Practice Print the array (for)

The nums array is set to {1, 2, 3, 4, 5}. Use a for (int i = 0; i < 5; i++) loop to print each element with std::cout << nums[i]; on a single line. The output must be 12345.

Starter code

main.cpp
#include <iostream>

int main() {
    int nums[5] = {1, 2, 3, 4, 5};
    // Print all elements with a for loop
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    int nums[5] = {1, 2, 3, 4, 5};
    for (int i = 0; i < 5; i++) {
        std::cout << nums[i];
    }
    std::cout << std::endl;
    return 0;
}

Expected output

12345

Questions and answers

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

1 Match each loop part to its role

Term Meaning
int i = 0 Start
i < 5 Condition
nums[i] i-th element of the array
i++ Increment

2 What does for (int i = 0; i < 5; i++) std::cout << nums[i]; do?

main.cpp
int nums[5] = {1,2,3,4,5};
for (int i = 0; i < 5; i++)
  std::cout << nums[i];
  • Prints the 5th element
  • Prints elements 0 to 4 Correct answer
  • Divides the array by 5
  • Forms an infinite loop

Explanation: i = 0,1,2,3,4 elements are printed.

3 Write the loop body

Question
int nums[3] = {10, 20, 30};
for (int i = 0; i < 3; i++) {
    std::cout << ____;
}
Answer
int nums[3] = {10, 20, 30};
for (int i = 0; i < 3; i++) {
    std::cout << nums[i];
}

Explanation: nums[i] gives the current element on each iteration.

All lessons in Beginner