Paramclasses Academy - Blog

Tutorials Details

What is Arrays in C++

What is Arrays in C++

October 15, 2026

Arrays are one of the most important concepts in C++. They let you store multiple values of the same data type under a single variable name and access each value using an index.

In this module, you’ll learn array declaration, initialization, indexing, updating elements, traversing arrays with loops, finding array size, two-dimensional arrays, and practical programming problems.

Learning objectives

By the end of this module, you should be able to:

  • Explain what an array is and why it is useful.

  • Declare and initialize arrays.

  • Read, print, and modify individual elements.

  • Traverse arrays using for and while loops.

  • Calculate sums, averages, minimums, and maximums.

  • Understand two-dimensional arrays and nested loops.

  • Avoid common indexing errors.

    Estimated time: 60–90 minutes

    Prerequisites: Modules 1–5, especially variables, conditions, and loops

1. What is an array?

An array is a collection of elements of the same data type stored in consecutive memory locations. Each element is accessed using an index.

For example, instead of declaring five separate variables for five marks, you can store all the marks in one array.

Without an array:

int mark1 = 75;
int mark2 = 82;
int mark3 = 91;
int mark4 = 68;
int mark5 = 88;

With an array:

int marks[5] = {75, 82, 91, 68, 88};

The array marks stores five integers under one name.

How array indexing works

C++ arrays use zero-based indexing. This means the first element is at index 0, not index 1.

Index 4

For an array of 5 elements, valid indices are 0, 1, 2, 3, and 4.

For this array:

int numbers[5] = {10, 20, 30, 40, 50};
  • numbers[0] is 10.

  • numbers[1] is 20.

  • numbers[2] is 30.

  • numbers[3] is 40.

  • numbers[4] is 50.

The last valid index is always one less than the number of elements.

2. Declaring an array

Syntax

dataType arrayName[arraySize];

Examples:

int ages[5];
float prices[10];
char letters[4];
double measurements[6];

Part

Meaning

int

Element data type

ages

Array name

[5]

Number of elements

A built-in array has a fixed size. For example, int ages[5] has space for five integer elements.

Important rules

  • All elements in a built-in array have the same element type.

  • The size of a built-in array is fixed after creation.

  • The valid index range is 0 through size - 1.

  • Accessing an invalid index causes undefined behavior in C++.

3. Initializing an array

Initialization assigns starting values to the elements.

Method 1: Initialize all elements

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

Method 2: Let the compiler determine the size

int numbers[] = {10, 20, 30};

Here, the compiler determines that the array contains three elements.

Method 3: Initialize some elements

int numbers[5] = {10, 20};

The first two elements are initialized to 10 and 20; the remaining elements are initialized to 0.

The array is effectively:

10 20 0 0 0

Method 4: Initialize all elements to zero

int numbers[5] = {};

All five elements are initialized to zero.

Note: A local built-in array declared without an initializer, such as int numbers[5];, does not automatically contain zeros. Its elements have indeterminate values. Initialize elements before reading them.

4. Accessing and modifying array elements

Use the array name followed by an index in square brackets.

Example 1: Print a specific element

#include 
using namespace std;

int main() {
    int marks[5] = {75, 82, 91, 68, 88};

    cout << marks[0] << endl;
    cout << marks[2] << endl;
    cout << marks[4] << endl;

    return 0;
}

Output

75
91
88

Example 2: Change an element

#include 
using namespace std;

int main() {
    int numbers[3] = {10, 20, 30};

    numbers[1] = 99;

    cout << numbers[0] << " ";
    cout << numbers[1] << " ";
    cout << numbers[2];

    return 0;
}

Output

10 99 30

The statement numbers[1] = 99; replaces the second element's value. The other elements remain unchanged.

Interactive practice: Array indexing

Given this array:

int a[5] = {12, 24, 36, 48, 60};

Choose an index

0

1

2

3

4

Choose an operation

Read the element

Change the element to 100

Result

a[2] = 36

5. Traversing an array using loops

Array traversal means visiting each element of an array, usually to read, print, or process its value.

Loops are ideal for array traversal because an array's valid indices form a predictable sequence.

Example 1: Print every element using a for loop

#include 
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};

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

    return 0;
}

Output

10 20 30 40 50

The variable i takes the values 0, 1, 2, 3, and 4. Each value selects one element.

Example 2: Traverse using a while loop

#include 
using namespace std;

int main() {
    int numbers[4] = {5, 10, 15, 20};
    int i = 0;

    while (i < 4) {
        cout << numbers[i] << " ";
        i++;
    }

    return 0;
}

Output

5 10 15 20

Example 3: Take input from the user

#include 
using namespace std;

int main() {
    int numbers[5];

    cout << "Enter 5 numbers: ";

    for (int i = 0; i < 5; i++) {
        cin >> numbers[i];
    }

    cout << "Array elements: ";

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

    return 0;
}

Example run

Enter 5 numbers: 3 7 12 8 15
Array elements: 3 7 12 8 15

The first loop reads values into the array. The second loop displays the stored values.

6. Finding the size of an array

When an array is declared in the same scope, you can use sizeof to calculate its number of elements.

#include 
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    int size = sizeof(numbers) / sizeof(numbers[0]);

    cout << "Array size = " << size;

    return 0;
}

Output

Array size = 5

Why does this work?

  • sizeof(numbers) gives the total size of the array in bytes.

  • sizeof(numbers[0]) gives the size of one element in bytes.

  • Dividing the total by the element size gives the number of elements.

This technique works for an actual built-in array in its original scope. When an array is passed to an ordinary function parameter, it is generally adjusted to a pointer, so sizeof on that parameter does not give the original array's size.

For modern C++, std::size(numbers) is another clear option when the relevant header is included and the array is still an actual array.

Safer size-based traversal

#include 
#include 
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    for (size_t i = 0; i < size(numbers); i++) {
        cout << numbers[i] << " ";
    }

    return 0;
}

Output

10 20 30 40 50

Here, size(numbers) returns the element count. size_t is an unsigned integer type commonly used for sizes and indices.

7. Practical array programs

Program 1: Calculate the sum of array elements

#include 
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    int sum = 0;

    for (int i = 0; i < 5; i++) {
        sum += numbers[i];
    }

    cout << "Sum = " << sum;

    return 0;
}

Output

Sum = 150

The accumulator sum starts at zero. Each array element is added to it.

Program 2: Calculate the average

#include 
using namespace std;

int main() {
    int marks[5] = {70, 80, 90, 60, 100};
    int sum = 0;
    int count = 5;

    for (int i = 0; i < count; i++) {
        sum += marks[i];
    }

    double average = static_cast(sum) / count;

    cout << "Average = " << average;

    return 0;
}

Output

Average = 80

The static_cast conversion ensures that the division is performed using floating-point arithmetic. This matters when the average is not a whole number.

Program 3: Find the largest element

#include 
using namespace std;

int main() {
    int numbers[5] = {25, 10, 75, 40, 60};
    int largest = numbers[0];

    for (int i = 1; i < 5; i++) {
        if (numbers[i] > largest) {
            largest = numbers[i];
        }
    }

    cout << "Largest = " << largest;

    return 0;
}

Output

Largest = 75

Start with the first element as the current largest value. Compare each remaining element with it and update largest when a bigger value is found.

Program 4: Find the smallest element

#include 
using namespace std;

int main() {
    int numbers[5] = {25, 10, 75, 40, 60};
    int smallest = numbers[0];

    for (int i = 1; i < 5; i++) {
        if (numbers[i] < smallest) {
            smallest = numbers[i];
        }
    }

    cout << "Smallest = " << smallest;

    return 0;
}

Output

Smallest = 10

Program 5: Search for a value

#include 
using namespace std;

int main() {
    int numbers[5] = {12, 25, 37, 48, 59};
    int target = 37;
    int position = -1;

    for (int i = 0; i < 5; i++) {
        if (numbers[i] == target) {
            position = i;
            break;
        }
    }

    if (position != -1) {
        cout << "Found at index " << position;
    } else {
        cout << "Not found";
    }

    return 0;
}

Output

Found at index 2

This is called a linear search. It checks elements one by one until the target is found or the array ends.

8. The range-based for loop

C++ also supports a range-based for loop, which lets you process each element without manually managing an index.

Syntax

for (dataType variable : arrayName) {
    // Use variable
}

Example: Print all elements

#include 
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    for (int value : numbers) {
        cout << value << " ";
    }

    return 0;
}

Output

10 20 30 40 50

Modify elements using a reference

A normal loop variable such as value is a copy of each element. To modify the original elements, use a reference:

#include 
using namespace std;

int main() {
    int numbers[] = {1, 2, 3, 4, 5};

    for (int &value : numbers) {
        value *= 2;
    }

    for (int value : numbers) {
        cout << value << " ";
    }

    return 0;
}

Output

2 4 6 8 10

The & in int &value means value refers directly to each array element, rather than being a separate copy.

Use an indexed loop when you need the index, an ordinary range-based loop when you only need the values, and a reference-based range loop when you want to modify each element.

9. Two-dimensional arrays

A two-dimensional array organizes elements into rows and columns. It is useful for representing tables, grids, and matrices.

Declaration and initialization

int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};

This array has 2 rows and 3 columns.

Visual representation of matrix[2][3]

1

[0][0]

2

[0][1]

3

[0][2]

4

[1][0]

5

[1][1]

6

[1][2]

The first index selects the row; the second selects the column.

For example:

  • matrix[0][0] is 1.

  • matrix[0][2] is 3.

  • matrix[1][1] is 5.

  • matrix[1][2] is 6.

Example 1: Print a matrix using nested loops

#include 
using namespace std;

int main() {
    int matrix[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };

    for (int row = 0; row < 2; row++) {
        for (int col = 0; col < 3; col++) {
            cout << matrix[row][col] << " ";
        }
        cout << endl;
    }

    return 0;
}

Output

1 2 3
4 5 6

The outer loop visits each row. The inner loop visits each column within that row.

Example 2: Calculate the sum of all matrix elements

#include 
using namespace std;

int main() {
    int matrix[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };

    int sum = 0;

    for (int row = 0; row < 2; row++) {
        for (int col = 0; col < 3; col++) {
            sum += matrix[row][col];
        }
    }

    cout << "Matrix sum = " << sum;

    return 0;
}

Output

Matrix sum = 21

Example 3: Input a 2 × 2 matrix

#include 
using namespace std;

int main() {
    int matrix[2][2];

    cout << "Enter 4 numbers:\n";

    for (int row = 0; row < 2; row++) {
        for (int col = 0; col < 2; col++) {
            cin >> matrix[row][col];
        }
    }

    cout << "Matrix:\n";

    for (int row = 0; row < 2; row++) {
        for (int col = 0; col < 2; col++) {
            cout << matrix[row][col] << " ";
        }
        cout << endl;
    }

    return 0;
}

Example run

Enter 4 numbers:
1 2 3 4
Matrix:
1 2
3 4

10. Common array mistakes

Mistake 1: Accessing an invalid index

int a[5] = {1, 2, 3, 4, 5};
cout << a[5]; // Invalid index

Valid indices are 0 to 4. Index 5 is outside the array.

Mistake 2: Using i <= size

for (int i = 0; i <= 5; i++)

For a five-element array, this attempts to access index 5. Use i < 5.

Mistake 3: Reading uninitialized values

int a[3];
cout << a[0]; // Not safely initialized

Initialize the array or assign a value before reading each element.

Mistake 4: Confusing an index with a value

a[2] means the element at index 2, which is the third element. It does not mean the value 2.

Mistake 5: Mixing up matrix rows and columns

For int matrix[2][3], the valid row indices are 0–1 and the valid column indices are 0–2.

11. Array vs individual variables

Feature

Individual variables

Array

Store multiple values

Separate names required

One name with multiple elements

Access

By variable name

By index

Same data type

Not required across variables

Yes, for built-in arrays

Repeated processing

Can require repetitive code

Easily combined with loops

Number of elements

Declared separately

Fixed size for built-in arrays

Practical note: Built-in arrays are excellent for learning indexing and memory layout. In larger modern C++ programs, std::array is useful for fixed-size collections, while std::vector is commonly used when the collection needs to grow or shrink dynamically.

12. Mini project — Student marks analyzer

Build a program that accepts five student marks, displays them, and calculates the total, average, highest mark, and lowest mark.

Complete code

#include 
using namespace std;

int main() {
    const int SIZE = 5;
    int marks[SIZE];
    int total = 0;

    cout << "Enter marks for 5 students:\n";

    for (int i = 0; i < SIZE; i++) {
        cin >> marks[i];
    }

    int highest = marks[0];
    int lowest = marks[0];

    for (int i = 0; i < SIZE; i++) {
        total += marks[i];

        if (marks[i] > highest) {
            highest = marks[i];
        }

        if (marks[i] < lowest) {
            lowest = marks[i];
        }
    }

    double average = static_cast(total) / SIZE;

    cout << "Marks: ";

    for (int i = 0; i < SIZE; i++) {
        cout << marks[i] << " ";
    }

    cout << "\nTotal = " << total;
    cout << "\nAverage = " << average;
    cout << "\nHighest = " << highest;
    cout << "\nLowest = " << lowest;

    return 0;
}

Example run

Enter marks for 5 students:
78 92 65 88 77
Marks: 78 92 65 88 77
Total = 400
Average = 80
Highest = 92
Lowest = 65

Project concepts

  • const int SIZE = 5 defines a fixed array size.

  • The first loop collects the marks.

  • The second loop computes the total, highest, and lowest values.

  • The average uses floating-point division.

  • The final loop displays all the stored marks.

This program assumes the user enters valid integer marks. An extended version could validate the permitted range, such as 0–100.

13. Hands-on exercises

Try to write each program yourself before checking your logic.

Exercise 1 · Easy

Print an array in reverse order

Given int a[5] = {10, 20, 30, 40, 50};, print the elements from last to first.

Expected output: 50 40 30 20 10

Exercise 2 · Easy

Count even numbers

Take 10 integers as input and count how many are even.

Hint: Check whether a[i] % 2 == 0.

Exercise 3 · Intermediate

Find the second-largest distinct value

Given an integer array, find its second-largest distinct value. Consider what should happen if no such value exists.

Hint: Track the largest and second-largest values carefully.

Exercise 4 · Intermediate

Copy one array into another

Create an array of five integers, copy every element into a second array, and print the copied array.

Exercise 5 · Intermediate

Add two matrices

Create two 2 × 2 integer matrices and calculate their element-by-element sum.

Example:

Matrix A:     Matrix B:
1 2           5 6
3 4           7 8

Sum:
6 8
10 12

Exercise 6 · Challenge

Remove duplicate values

Given an array of integers, display each distinct value only once. Preserve the order in which values first appear.

14. Interactive knowledge-check quiz

Answer all seven questions to evaluate your understanding of arrays in C++.

Arrays quiz

0 / 7 answered

1. What is the index of the first element in a C++ built-in array?

1

0

-1

It depends on the data type

2. How many elements can int a[6] store?

5

6

7

It has no fixed size

3. What is the value of a[2] for int a[4] = {10, 20, 30, 40};?

10

20

30

40

4. Which condition safely traverses every element of a five-element array using i starting at 0?

i <= 5

i < 5

i < 6

i >= 0

5. What does a range-based loop with int &value allow you to do?

Automatically sort the array

Modify each original element through the reference

Change the array's fixed size

Access invalid indices safely

6. For int matrix[2][3], how many elements are there?

2

3

5

6

7. What is the result of adding {1, 2, 3} and {4, 5, 6} element by element?

{4, 10, 18}

{5, 7, 9}

{1, 2, 3, 4, 5, 6}

{6, 7, 8}

Submit quiz

Select an answer for every question before submitting.

15. Module 6 completion checklist

Learning progress

0 / 7

I understand zero-based indexing.

I can declare, initialize, read, and update arrays.

I can traverse arrays using loops.

I can calculate sums, averages, minimums, and maximums.

I understand range-based loops and references.

I can work with two-dimensional arrays.

I have attempted the exercises and quiz.