C++: Array Basics
Last updated: 2026-08-26
In previous lessons, each variable could only store one value.
But if you need to store 100 students' scores, you can't declare 100 variables, right?
Arrays solve this problem — a contiguous block of memory used to store multiple values of the same type.
1. What is an Array?
(1) 1.1 Arrays in Everyday Life
| Real-life Analogy | Program Equivalent |
|---|---|
| A row of mailboxes (each with a different number) | Array (each element has a different index) |
| A carton of eggs (12 eggs, numbered 1-12) | Array (12 elements, indices 0-11) |
Characteristics of arrays:
- All elements are the same type (all
int, or alldouble) - Contiguous memory (elements are stored one after another)
- Indices start from 0 (not from 1!)
(2) 1.2 Why Do We Need Arrays?
Without arrays (bad example):
▶ Example 2: Basic Programming Practice (Difficulty ⭐)
#include <iostream>
int main() {
int score1 = 90;
int score2 = 85;
int score3 = 92;
// ... need to declare 100 variables!
return 0;
}
Output:
(Program output)
With arrays (good example):
#include <iostream>
int main() {
int scores[100]; // array that can hold 100 integers
// use loop to assign values
for (int i = 0; i < 100; i++) {
scores[i] = 0;
}
return 0;
}
2. Array Declaration and Initialization
(1) 2.1 Declaring an Array
Syntax:
Type arrayName[Number of elements];
Example:
int scores[5]; // array that can hold 5 integers
double prices[10]; // array that can hold 10 doubles
char letters[26]; // array that can hold 26 chars
💡 Key point: Array indices start from 0, so scores[5] has indices from 0 to 4 (not 1 to 5).
(2) 2.2 Initializing an Array
Method 1: Initialize at declaration
int scores[5] = {90, 85, 92, 78, 88};
Method 2: Partial initialization
int scores[5] = {90, 85}; // only initialize first two, rest become 0 automatically
Method 3: Let the compiler infer the size
int scores[] = {90, 85, 92, 78, 88}; // compiler infers size as 5
💡 Tip: Method 3 is recommended — if you change the array contents later, you don't need to manually update the size.
3. Accessing Array Elements
(1) 3.1 Reading Elements
Syntax:
arrayName[Index]
Example:
#include <iostream>
int main() {
int scores[5] = {90, 85, 92, 78, 88};
std::cout << "First score: " << scores[0] << std::endl; // 90
std::cout << "Third score: " << scores[2] << std::endl; // 92
std::cout << "Last score: " << scores[4] << std::endl; // 88
return 0;
}
(2) 3.2 Modifying Elements
#include <iostream>
int main() {
int scores[5] = {90, 85, 92, 78, 88};
scores[1] = 95; // change second score to 95
std::cout << "Modified second score: " << scores[1] << std::endl; // 95
return 0;
}
4. Traversing an Array
(1) 4.1 Traversing with a for Loop
#include <iostream>
int main() {
int scores[5] = {90, 85, 92, 78, 88};
std::cout << "All scores: " << std::endl;
for (int i = 0; i < 5; i++) {
std::cout << "No. " << i + 1 << " Score: " << scores[i] << std::endl;
}
return 0;
}
💡 Key point: When traversing an array, the loop condition is typically i < array_size, rather than i <= array_size - 1 (which is more error-prone).
5. Array Size
(1) 5.1 Calculating the Number of Elements with sizeof
#include <iostream>
int main() {
int scores[5] = {90, 85, 92, 78, 88};
int size = sizeof(scores) / sizeof(scores[0]); // calculate array size
std::cout << "Array size:" << size << std::endl; // 5
return 0;
}
How it works:
sizeof(scores)— total bytes of the entire array (5 × 4 = 20 bytes)sizeof(scores[0])— bytes of one element (4 bytes)- Dividing gives the number of elements
💡 Tip: This method only works for actual arrays, not pointers (covered later).
6. Arrays as Function Parameters
(1) 6.1 The Problem: Arrays Decay into Pointers
When you pass an array to a function, it decays into a pointer (losing size information).
#include <iostream>
// array as parameter, need to pass size
void printArray(int arr, int size) {
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
int main() {
int scores[5] = {90, 85, 92, 78, 88};
printArray(scores, 5); // pass array name (which is address of first element)
return 0;
}
💡 Key point: When passing an array as a parameter, you must also pass the size.
7. Common Errors
(1) 7.1 Array Out of Bounds
Error example:
#include <iostream>
int main() {
int scores[5] = {90, 85, 92, 78, 88};
std::cout << scores[5] << std::endl; // ERROR: out of bounds! max index is 4
return 0;
}
Consequence: Reading garbage values, or program crash.
💡 Tip: C++ does not automatically check array bounds! This is one reason C++ is fast, but also a common source of bugs.
(2) 7.2 Using a Variable as Array Size (Before C++11)
Error example (before C++11):
#include <iostream>
int main() {
int n = 5;
int scores[n]; // ERROR (before C++11): array size must be compile-time constant
return 0;
}
Correct approach (supported after C++11):
#include <iostream>
int main() {
int n = 5;
int scores[n]; // OK (after C++11): Variable Length Array (VLA) supported
return 0;
}
💡 Better approach: Use std::vector (covered later), which supports dynamic sizes.
8. Practice: Calculating the Average Score
▶ Example 1: Calculating Average Score (Difficulty ⭐⭐)
#include <iostream>
#include <iomanip>
int main() {
int scores[5] = {90, 85, 92, 78, 88};
int sum = 0;
// calculate total score
for (int i = 0; i < 5; i++) {
sum += scores[i];
}
// calculate average score
double average = static_cast<double>(sum) / 5;
std::cout << std::fixed << std::setprecision(2);
std::cout << "Total: " << sum << std::endl;
std::cout << "Average: " << average << std::endl;
return 0;
}
Output:
Total: 433
Average: 86.60
❓ FAQ
▶ Example 3: Array Traversal (Difficulty ⭐)
#include <iostream>
int main() {
int scores[] = {85, 92, 78, 90, 88};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += scores[i];
}
double avg = sum / 5.0;
std::cout << "Average: " << avg << std::endl;
return 0;
}
Output:
Average: 86.6
{}, and the number of elements can be calculated using sizeof(arr) / sizeof(arr[0]).
📖 Summary
- Arrays are a contiguous block of memory used to store multiple values of the same type
- Array indices start from 0
- Declaring an array:
Type arrayName[Size]; - Initializing an array:
Type arrayName = {val1, val2, ...}; - Accessing elements:
arrayName[Index] - Traversing an array: use a
forloop - When passed as a parameter, arrays decay into pointers and require passing the size separately
📝 Exercises
-
Basic (Difficulty ⭐): Declare a
doublearray to store 5 prices, then use a loop to calculate the total price. -
Intermediate (Difficulty ⭐⭐): Write a function
int findMax(int arr, int size)that finds the maximum value in an array. Test it inmain. -
Challenge (Difficulty ⭐⭐⭐): Write a program that lets the user enter 10 integers, stores them in an array, then:
-
Finds the maximum and minimum values
-
Calculates the average score
-
Outputs all scores above the average
- Array: a contiguous memory collection of elements of the same type
- Indices start from 0; size must be specified at declaration
- Array initialization list
{}can omit the size - Traverse arrays using for loops with indices
- The array name is the address of the first element and cannot be modified
13. 🚀 Next Step
Now that you've learned array basics, let's move on to Multi-dimensional Arrays (Lesson 17) — handling tabular data (such as matrices, game boards).