LearnContact
Lesson 1410 min read

Arrays

Creating thousands of variables for 1,000 employees is neither practical nor efficient. In this lesson, you will learn how C++ uses arrays to store multiple values of the same data type using a single variable.

Introduction

In the previous lesson, you learned about functions, which help organize code into reusable blocks. Now consider a different problem: storing many related values.

Suppose you want to store the marks of five students. Without arrays, you could create five separate variables such as marks1, marks2, marks3, marks4, and marks5.

Without an Array
int marks1 = 80;
int marks2 = 75;
int marks3 = 90;
int marks4 = 65;
int marks5 = 88;

This approach may work for a few values, but it becomes impractical when a program needs to store hundreds or thousands of related values.

The Problem

Creating hundreds or thousands of separate variables makes programs difficult to write, process, and maintain. C++ solves this problem with arrays.

What is an Array?

An array is a collection of elements of the same data type stored in contiguous memory locations.

Instead of creating a separate variable for every value, an array stores multiple related values under one variable name. Each individual value is called an element and is accessed using an index.

Simple Array
int marks[5] = {80, 75, 90, 65, 88};
Simple Definition

An array stores multiple values of the same data type under one variable name.

Why Do We Need Arrays?

Without Arrays

  • A separate variable is required for every value.
  • Programs become lengthy and confusing.
  • Processing large amounts of related data becomes difficult.
  • Repeated operations require repetitive code.
  • Managing hundreds or thousands of values becomes impractical.

With Arrays

  • Multiple related values are stored under one name.
  • Code duplication is reduced.
  • Elements are accessed easily using indexes.
  • Loops can process all elements efficiently.
  • Programs become shorter and easier to organize.
Without an Array
int mark1 = 80;
int mark2 = 75;
int mark3 = 90;
int mark4 = 65;
int mark5 = 88;
With an Array
int marks[5] = {80, 75, 90, 65, 88};
One Name, Multiple Values

Arrays make it possible to manage a group of related values using one variable name and different indexes.

Real-World Analogy

Imagine a classroom where each student is identified by a roll number. Instead of creating a completely separate system for every student, the roll number is used to locate a particular student.

Classroom Analogy
Roll Number  →  Student Name

0            →  Rahul
1            →  Amit
2            →  Priya
3            →  Neha
4            →  Karan

An array works similarly. The array name represents the complete collection, while an index identifies a particular element.

Array Name
Choose Index
Locate Element
Access Value
Important Difference

C++ array indexes begin at 0. Therefore, the first element is at index 0, the second element is at index 1, and so on.

Characteristics of Arrays

Multiple Values

An array can store multiple related values under one variable name.

Same Data Type

All elements of a traditional array have the same data type.

Contiguous Memory

Array elements are stored next to one another in contiguous memory locations.

Indexed Elements

Every element is identified and accessed using an index.

0️⃣ Zero-Based Indexing

The first element is stored at index 0.

Fixed Size

The size of a traditional built-in array is fixed after declaration.

Five Important Properties

Arrays store multiple values, use one element type, use indexes, begin indexing at 0, and store elements contiguously.

Array Declaration & Initialization

Before using an array, it must be declared. An array can also be initialized with values when it is declared.

General Syntax
data_type array_name[size];
Declaration
int marks[5];

Understanding the Declaration

  • int is the data type of every element.
  • marks is the array name.
  • 5 is the number of elements the array can contain.
Initialization
int marks[5] = {80, 75, 90, 65, 88};

The values inside the braces are assigned to array elements in order, beginning with index 0.

IndexValue
080
175
290
365
488
Size Inferred from Initializer
int marks[] = {80, 75, 90, 65, 88};

When an initializer list is provided, the compiler can determine the array size from the number of values.

Memory Representation

Array elements are stored in contiguous memory locations. This means each element is placed directly next to the previous element in memory.

Example Array
int marks[5] = {80, 75, 90, 65, 88};
Memory Layout
Index:     0      1      2      3      4
           │      │      │      │      │
           ▼      ▼      ▼      ▼      ▼
Value:    80     75     90     65     88

Memory:  [80] → [75] → [90] → [65] → [88]

Because the elements are contiguous, the location of an element can be calculated efficiently from the array starting address and the element index.

Indexing Starts from 0

For an array containing five elements, the valid indexes are 0, 1, 2, 3, and 4. Index 5 is outside the array.

Array Index & Accessing Elements

Every element in an array has a unique index. To access an element, write the array name followed by the required index inside square brackets.

General Syntax
array_name[index]
Accessing Elements
marks[0]  →  80  (First element)
marks[1]  →  75
marks[2]  →  90
marks[3]  →  65
marks[4]  →  88  (Last element)
Reading an Element
std::cout << marks[0];
Output
80
Finding the Last Index

For an array of size n, the first index is 0 and the last valid index is n - 1.

Example 1: Declaring and Displaying

Example 1
#include <iostream>

int main()
{
    int marks[5] = {80, 75, 90, 65, 88};

    std::cout << marks[0] << std::endl;
    std::cout << marks[1] << std::endl;
    std::cout << marks[2] << std::endl;
    std::cout << marks[3] << std::endl;
    std::cout << marks[4];

    return 0;
}

Explanation

  • int marks[5] creates an integer array containing five elements.
  • The initializer list provides the five initial values.
  • marks[0] accesses the first element.
  • marks[1] accesses the second element.
  • marks[4] accesses the fifth and final element.
Output
80
75
90
65
88

Example 2: Updating an Element

An individual array element can be updated by assigning a new value to its index.

Example 2
#include <iostream>

int main()
{
    int marks[5] = {80, 75, 90, 65, 88};

    marks[2] = 95;

    std::cout << marks[2];

    return 0;
}
Access marks[2]
Current Value = 90
Assign New Value = 95
Element Updated
Display 95
Before Updating
Index:  0   1   2   3   4
Value: 80  75  90  65  88
After Updating
Index:  0   1   2   3   4
Value: 80  75  95  65  88
Output
95

Example 3: Using a Loop with an Array

One of the greatest advantages of arrays is that their elements can be processed efficiently using loops.

Instead of writing a separate output statement for every element, a loop can change the index automatically.

Example 3
#include <iostream>

int main()
{
    int marks[5] = {80, 75, 90, 65, 88};

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

    return 0;
}

How the Loop Works

  • i begins with the value 0.
  • marks[i] initially accesses marks[0].
  • After each iteration, i increases by 1.
  • The next iteration accesses the next array element.
  • The loop continues while i is less than 5.
  • When i becomes 5, the condition becomes false and the loop stops.
IterationiElementValue
10marks[0]80
21marks[1]75
32marks[2]90
43marks[3]65
54marks[4]88
Output
80
75
90
65
88
Arrays and Loops Work Together

The loop variable can be used as the array index, making it possible to process every element with a small amount of code.

Program Execution Flow

Program Starts
Create Array
Store Initial Elements
Initialize Index
Check Loop Condition
Access Element Using Index
Process or Display Element
Increase Index
Repeat Until All Elements Are Processed
Program Ends

The array is created first and its values are stored. A loop then uses an index to access one element at a time until every valid element has been processed.

Advantages & Limitations

Advantages

  • Store multiple values using one variable name.
  • Reduce unnecessary code duplication.
  • Improve organization and readability.
  • Work efficiently with loops.
  • Provide direct access through indexes.
  • Store elements contiguously in memory.

Limitations

  • All elements use the same data type.
  • The size of a built-in array is fixed.
  • The array cannot automatically grow or shrink.
  • Insertion in the middle may require shifting elements.
  • Deletion may require reorganizing remaining elements.
  • Accessing outside valid bounds causes undefined behavior.
Arrays Are Best for Fixed Collections

Traditional arrays are useful when the number of elements is known and a fixed-size collection is appropriate.

Real-World Applications

Student Management

Student marks, attendance records, roll numbers, and subject scores.

Banking

Monthly transactions, interest records, and account activity.

Games

Player scores, inventory slots, positions, and level data.

Scientific Applications

Sensor readings, measurements, experiment results, and temperature records.

E-Commerce

Product prices, stock quantities, ratings, and order values.

Data Processing

Collections of numbers used for searching, sorting, and calculations.

Foundation for Advanced Data Structures

Understanding arrays prepares you for strings, multidimensional arrays, vectors, matrices, searching, sorting, and many advanced data structures.

Common Beginner Mistakes

Starting Index from 1

The first element of a C++ array is at index 0, not index 1.

Accessing an Invalid Index

For an array of size 5, valid indexes are 0 through 4. Index 5 is outside the array.

Using the Wrong Loop Condition

Using <= with the array size can cause the loop to access one element beyond the array.

Mixing Data Types

A traditional array stores elements of one declared data type.

Using Uninitialized Elements

Reading uninitialized local array elements can produce indeterminate values.

Confusing Size with Last Index

An array of size 5 has a last valid index of 4.

Starting from the Wrong Index
// ❌ This accesses the second element
marks[1];

// ✅ This accesses the first element
marks[0];
Accessing Outside the Array
int marks[5];

// ❌ Invalid index
marks[5];

// Valid indexes:
// 0, 1, 2, 3, 4
Out-of-Bounds Access

Built-in C++ arrays do not automatically check whether an index is valid. Accessing outside the array bounds results in undefined behavior.

Wrong Loop Condition
// ❌ Incorrect
for (int i = 0; i <= 5; i++)
{
    std::cout << marks[i];
}

// ✅ Correct
for (int i = 0; i < 5; i++)
{
    std::cout << marks[i];
}
Uninitialized Array
int numbers[5];

// Values are not automatically initialized
// for a local built-in array
Value Initialization
int numbers[5] = {};

Best Practices

  • Use meaningful array names such as studentMarks instead of generic names such as arr.
  • Remember that indexing begins at 0.
  • Never intentionally access an index outside the valid range.
  • Use loops instead of repetitive statements when processing multiple elements.
  • Initialize arrays whenever appropriate.
  • Keep the array size consistent with loop conditions.
  • Use named constants instead of repeating unexplained size values.
  • Use the same size value for declaration and traversal logic.
  • Choose arrays when a fixed-size collection is appropriate.
  • Prefer modern C++ containers such as std::array or std::vector when their features better match the problem.
Using a Named Size
const int SIZE = 5;

int marks[SIZE] = {80, 75, 90, 65, 88};

for (int i = 0; i < SIZE; i++)
{
    std::cout << marks[i] << std::endl;
}
Avoid Repeating Magic Numbers

Using a named size makes the relationship between the array declaration and loop condition easier to understand and maintain.

Frequently Asked Questions

What is an array?

An array is a collection of elements of the same data type stored in contiguous memory locations.

Why are arrays used?

Arrays allow multiple related values to be stored and processed using one variable name.

What is the first index of an array?

The first index of a C++ array is 0.

What is the last index of an array?

For an array of size n, the last valid index is n - 1.

Can an array store different data types?

A traditional array stores elements of one declared data type.

Why are arrays useful with loops?

A loop can use its control variable as an index to process each array element without repetitive code.

Can a built-in array grow automatically?

No. The size of a built-in array is fixed and it does not automatically grow or shrink.

What happens if I access an invalid index?

Accessing outside the bounds of a built-in array causes undefined behavior.

Are array elements stored together in memory?

Yes. Elements of an array are stored in contiguous memory locations.

Can an array element be updated?

Yes. An element can be changed by assigning a new value to its index.

Key Takeaways

  • Arrays store multiple related values under one variable name.
  • All elements of a traditional array use the same data type.
  • Array elements are stored in contiguous memory locations.
  • Each element is accessed using an index.
  • Array indexing starts from 0.
  • For an array of size n, the last valid index is n - 1.
  • Arrays can be initialized when they are declared.
  • Individual elements can be read and updated.
  • Loops make array processing efficient.
  • Built-in array size is fixed after declaration.
  • Accessing outside valid bounds causes undefined behavior.
  • Arrays provide a foundation for more advanced data structures.

Summary

Arrays are one of the most important foundational data structures in C++. They allow programmers to store multiple related values of the same data type under one variable name.

Each array element is stored in contiguous memory and accessed using an index. Because indexing starts at 0, an array of size n has valid indexes from 0 to n - 1.

By combining arrays with loops, programmers can process large collections of data using concise and reusable logic. Understanding declaration, initialization, indexing, updating, traversal, memory layout, and array bounds prepares you for strings, multidimensional arrays, searching, sorting, and advanced data structures.

Next Lesson →

Strings