C++ Basics · Chapter 5

Arrays and Vectors in C++: Description & Usage With Examples

Learn how to store and manage collections of data using arrays and vectors. Master declaration, initialization, loops, and dynamic list operations.

By Arj Updated July 2025 14 min read No prior experience needed
What you'll learn
  • What arrays and vectors are and why they are useful
  • How to declare and initialize arrays
  • How to loop through arrays for input and output
  • How vectors work and when to use them over arrays
  • Key vector functions: push_back, size, clear, and empty

1Why use arrays and vectors?

When you need to store multiple values of the same type, like a list of test scores, student names, or temperatures, you need a way to group them together. That is exactly what arrays and vectors do.

Without an array:

cpp
int m1, m2, m3, m4, m5;

With an array:

cpp
int marks[5];

Arrays group values together, making your code cleaner, easier to manage, and more scalable. Vectors take this a step further by allowing dynamic resizing.

2Arrays in C++

An array is a fixed-size collection of elements of the same data type. The size must be known at compile time.

Declaration

cpp
int numbers[5]; // creates space for 5 integers

Initialization

cpp
int numbers[5] = {10, 20, 30, 40, 50};

You can also omit the size if you are initializing:

cpp
int numbers[] = {10, 20, 30}; // compiler counts 3 elements

Accessing elements

Array indexing starts at 0. The first element is at index 0, the second at index 1, and so on.

cpp
cout << numbers[0]; // prints 10
numbers[2] = 99;    // changes the 3rd element to 99
Output10

3Looping through arrays

Use a for loop to access each element in an array. The loop counter serves as the index.

cpp
int scores[5] = {88, 76, 92, 85, 69};

for (int i = 0; i < 5; i++) {
    cout << "Score " << i << ": " << scores[i] << endl;
}
OutputScore 0: 88 Score 1: 76 Score 2: 92 Score 3: 85 Score 4: 69

4Inputting into an array

You can read values from the user directly into an array using cin inside a loop.

cpp
int marks[5];

cout << "Enter marks of 5 students: ";
for (int i = 0; i < 5; i++) {
    cin >> marks[i];
}

5Common mistakes with arrays

1. Going out of bounds
Accessing numbers[5] in a size 5 array causes undefined behavior. Valid indices are 0 to 4. The compiler will not stop you, but your program may crash or behave unpredictably.
2. Using the wrong size in loops
Always match your loop condition with the array size. If the array has 5 elements, the loop should run for i < 5, not i <= 5.
3. Arrays are fixed size
Once declared, you cannot change an array's size. This is why vectors are often a better choice for dynamic data.

6When to use vectors

Arrays are fixed in size. If you need a collection that can grow or shrink, use a vector. Vectors are part of the C++ Standard Template Library (STL).

To use vectors, include:

cpp
#include <vector>
using namespace std;

Declaring vectors

cpp
vector<int> numbers; // empty vector of integers

Initialization

cpp
vector<int> scores = {85, 90, 78};

Add elements

cpp
scores.push_back(95); // adds 95 to the end

Access elements

cpp
cout << scores[0]; // prints 85
scores[1] = 100;   // changes the second element to 100

7Looping through vectors

You can loop through a vector using a traditional for loop with size(), or use a range-based for loop.

Traditional loop

cpp
vector<int> values = {10, 20, 30, 40};

for (int i = 0; i < values.size(); i++) {
    cout << values[i] << endl;
}

Range-based for loop (C++11 and later)

cpp
for (int val : values) {
    cout << val << endl;
}
Output10 20 30 40

8Vector functions you should know

FunctionDescription
push_back(x)Adds x to the end of the vector
size()Returns the number of elements
clear()Removes all elements
empty()Returns true if the vector is empty
Check before accessing
Always check empty() before accessing elements if there is a chance the vector could be empty. Accessing an empty vector causes undefined behavior.

9Example: Average of N numbers using a vector

This example demonstrates reading N values from the user, storing them in a vector, and calculating the average.

cpp
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cout << "Enter number of elements: ";
    cin >> n;

    vector<int> nums;
    int input;
    int sum = 0;

    for (int i = 0; i < n; i++) {
        cin >> input;
        nums.push_back(input);
        sum += input;
    }

    double average = (double) sum / nums.size();
    cout << "Average: " << average << endl;

    return 0;
}
Sample runEnter number of elements: 4 10 20 30 40 Average: 25

10Mini exercises

Try these yourself
  1. Create an array of size 10 and store the first 10 square numbers (1, 4, 9, 16, ...).
  2. Write a program that finds the maximum value in an array of integers.
  3. Use a vector to read N values from the user, and then print only the even numbers.
  4. Initialize a vector with {1, 2, 3}, then add 4 and 5 using push_back, and print all values.

Hint: For the square numbers, multiply i * i inside the loop. For even numbers, check num % 2 == 0.

11Quiz yourself

Arrays and Vectors Quiz
Question 1 of 10
Coming up next
2D Arrays
Learn how to work with matrices, grids, and board-style problems using two-dimensional arrays in C++.
Continue to Chapter 6

Stop wrestling with confusion.

Join thousands of students mastering Computer Science without the academic jargon.

From syntax to systems. We break down the hardest ideas in computer science so you can actually build things.

© 2026 Painless Programming. Built for students.
Scroll to Top