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.
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.
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.
int marks[5] = {80, 75, 90, 65, 88};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.
int mark1 = 80;
int mark2 = 75;
int mark3 = 90;
int mark4 = 65;
int mark5 = 88;int marks[5] = {80, 75, 90, 65, 88};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.
Roll Number → Student Name
0 → Rahul
1 → Amit
2 → Priya
3 → Neha
4 → KaranAn array works similarly. The array name represents the complete collection, while an index identifies a particular element.
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.
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.
data_type array_name[size];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.
int marks[5] = {80, 75, 90, 65, 88};The values inside the braces are assigned to array elements in order, beginning with index 0.
| Index | Value |
|---|---|
| 0 | 80 |
| 1 | 75 |
| 2 | 90 |
| 3 | 65 |
| 4 | 88 |
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.
int marks[5] = {80, 75, 90, 65, 88};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.
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.
array_name[index]marks[0] → 80 (First element)
marks[1] → 75
marks[2] → 90
marks[3] → 65
marks[4] → 88 (Last element)std::cout << marks[0];80For an array of size n, the first index is 0 and the last valid index is n - 1.
Example 1: Declaring and Displaying
#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.
80
75
90
65
88Example 2: Updating an Element
An individual array element can be updated by assigning a new value to its index.
#include <iostream>
int main()
{
int marks[5] = {80, 75, 90, 65, 88};
marks[2] = 95;
std::cout << marks[2];
return 0;
}Index: 0 1 2 3 4
Value: 80 75 90 65 88Index: 0 1 2 3 4
Value: 80 75 95 65 8895Example 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.
#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.
| Iteration | i | Element | Value |
|---|---|---|---|
| 1 | 0 | marks[0] | 80 |
| 2 | 1 | marks[1] | 75 |
| 3 | 2 | marks[2] | 90 |
| 4 | 3 | marks[3] | 65 |
| 5 | 4 | marks[4] | 88 |
80
75
90
65
88The 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
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.
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.
Understanding arrays prepares you for strings, multidimensional arrays, vectors, matrices, searching, sorting, and many advanced data structures.
Common Beginner Mistakes
The first element of a C++ array is at index 0, not index 1.
For an array of size 5, valid indexes are 0 through 4. Index 5 is outside the array.
Using <= with the array size can cause the loop to access one element beyond the array.
A traditional array stores elements of one declared data type.
Reading uninitialized local array elements can produce indeterminate values.
An array of size 5 has a last valid index of 4.
// ❌ This accesses the second element
marks[1];
// ✅ This accesses the first element
marks[0];int marks[5];
// ❌ Invalid index
marks[5];
// Valid indexes:
// 0, 1, 2, 3, 4Built-in C++ arrays do not automatically check whether an index is valid. Accessing outside the array bounds results in undefined behavior.
// ❌ Incorrect
for (int i = 0; i <= 5; i++)
{
std::cout << marks[i];
}
// ✅ Correct
for (int i = 0; i < 5; i++)
{
std::cout << marks[i];
}int numbers[5];
// Values are not automatically initialized
// for a local built-in arrayint 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.
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;
}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.