New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› C++› Arrays and Vectors

Arrays and Vectors

💻 C++

Store collections with raw arrays and the safer, resizable std::vector.

Lesson 5 of 9 Tutorial
0 of 9 completed

A raw array has a fixed size and does not know its own length. std::vector grows, shrinks and manages its memory.

By the end of this lesson you can:
  • Create and loop over arrays.
  • Use vector methods.
  • Avoid out-of-bounds access.

Raw Arrays

A raw array has a fixed size set at compile time. There is no bounds checking, so reading past the end is undefined behaviour.

int scores[5] = {88, 74, 91, 65, 52};

for (int i = 0; i < 5; i++) {
    std::cout << scores[i] << "\n";
}

std::vector

A vector knows its size, grows automatically and is the default choice for collections.

#include <vector>

std::vector<int> scores = {88, 74, 91};
scores.push_back(65);

for (int score : scores) {
    std::cout << score << "\n";
}

std::cout << scores.size() << "\n";

Safe Access

Use at() when an index comes from outside your control. It throws instead of reading invalid memory. Use range-based for loops when you do not need the index.

Warning Undefined behaviour may appear to work. Out-of-bounds access can corrupt memory silently, so prefer vector and at().

Practice

  1. Create a vector of five names and print them.
  2. Calculate the total and average of a vector of scores.
  3. Explain why vector is safer than a raw array.

Hands-on exercise

Read six scores into a vector.
1. Print the highest and lowest.
2. Print the average to two decimal places.
3. Print each score above the average.

Recap

Raw arrays are fixed and unsafe at the edges. std::vector is the practical default for collections.

Example

int scores[5] = {88, 74, 91, 65, 52};

for (int i = 0; i < 5; i++) {
    std::cout << scores[i] << "
";
}

Exercises

Exercise 1. Score report Medium
Read six scores into a vector.
1. Print the highest and lowest.
2. Print the average to two decimal places.
3. Print each score above the average.
C++ exercise-1.txt
Expected Output
High, low, average and the above-average scores.

Lesson Nav

Lesson sections