CodeBlanks Logo Icon CodeBlanks

Summary - Arrays

Use C-style and std::array to write a grade table.

Summary - Arrays

In this group you learned ways to hold fixed-size data in C++: C-style arrays, std::array, multidimensional arrays and iterating with loops. Each has its own advantage and use case.

Now you have two tasks. First you will sum three grades with a C-style array, then print four numbers with std::array using range-based for. Such accumulation and loop tasks appear all the time in real programs, for example in grade averages, temperature readings or stock counts.

Practice Grade table (C-style)

The grades array is set to {85, 90, 78}. Use a for (int i = 0; i < 3; i++) loop to accumulate with sum += grades[i] and print it with std::cout << sum. The output must be 253.

Starter code

main.cpp
#include <iostream>

int main() {
    int grades[3] = {85, 90, 78};
    int sum = 0;
    // Compute and print the sum
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    int grades[3] = {85, 90, 78};
    int sum = 0;
    for (int i = 0; i < 3; i++) {
        sum += grades[i];
    }
    std::cout << sum << std::endl;
    return 0;
}

Expected output

253

Practice Print with std::array

The std::array<int, 4> nums = {2, 4, 6, 8}; is given. Use a for (int x : nums) loop to print each element with std::cout << x; on a single line. The output must be 2468.

Starter code

main.cpp
#include <iostream>
#include <array>

int main() {
    std::array<int, 4> nums = {2, 4, 6, 8};
    // Print with range-based for
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <array>

int main() {
    std::array<int, 4> nums = {2, 4, 6, 8};
    for (int x : nums) {
        std::cout << x;
    }
    std::cout << std::endl;
    return 0;
}

Expected output

2468

Questions and answers

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

1 What does std::array<int, 5> a; a.size() return?

main.cpp
std::array<int, 5> a;
a.size()
  • 3
  • 0
  • 5 Correct answer
  • Unclear

Explanation: The size template parameter is 5; size() returns 5.

2 Match each array type to its scenario

Term Meaning
int nums[5] C-style array
std::array<int, 5> Modern array
int matrix[2][3] Multidimensional
nums[i] Array access

3 Write the C-style array declaration

Question
int ____[4] = {2, 4, 6, 8};
Answer
int nums[4] = {2, 4, 6, 8};

Explanation: The array name is nums; plural naming fits arrays.

All lessons in Beginner