An array stores an ordered group of values of the same type. Every element is accessed by index, and the array length is fixed when it is created.
Creating arrays
Use an array initializer when the values are known. int counts[4]{} creates four zero-initialized slots. The element type comes before the variable name, and brackets mean “a group of this type.”
int main() {
int scores[] = {88, 91, 76, 95, 83};
int counts[4]{};
counts[0] = 12;
counts[1] = 9;
return 0;
}Using {} to initialize a numeric array sets every element to 0; an uninitialized local array does not receive automatic default values. The slot count is decided when the array is created.
KNOWLEDGE QUIZ
Accessing array elements
Array indexes start at 0, so the first element is scores[0]. An array of length 5 has indexes 0 through 4. Accessing scores[5] causes undefined behavior.
#include <iostream>
using namespace std;
int main() {
int scores[] = {88, 91, 76, 95, 83};
cout << scores[0] << endl; // 88
cout << scores[4] << endl; // 83
scores[2] = 80;
cout << scores[2] << endl; // 80
return 0;
}Array index spotlight
Select any slot and let a C++ expression point to exactly one value. Valid indexes always run from 0 through score_count-1.
KNOWLEDGE QUIZ
Array length and loops
Built-in arrays have no length field. This example first computes score_count = 5; the last valid index is score_count - 1.
#include <iostream>
using namespace std;
int main() {
int scores[] = {88, 91, 76, 95, 83};
const int score_count = 5;
for (int i = 0; i < score_count; i++) {
cout << "scores[" << i << "] = " << scores[i] << endl;
}
for (int score : scores) {
cout << score << endl;
}
return 0;
}KNOWLEDGE QUIZ
Fixed length and common operations
You can rewrite existing elements and search with a loop. Neither action adds or removes slots.
#include <iostream>
using namespace std;
int main() {
int values[] = {4, 0, 7, 0, 2, 9};
values[2] = 5;
for (int value : values) {
cout << value << ' ';
}
return 0;
}KNOWLEDGE QUIZ
Move zeroes to the end of an array
Given {0, 1, 0, 3, 12}, move every zero to the end in place while preserving the order of nonzero elements.
- Scan every element with a read index.
- Use a write index for the next nonzero destination.
- Fill the remaining cells with zero after the scan.
Reverse an integer array in place
Use two indexes, left and right, moving inward while swapping values. Transform {2, 4, 6, 8, 10} into {10, 8, 6, 4, 2}.
- Point left at the first element and right at the last.
- Swap both ends, then move both indexes inward.
- Stop when left is no longer less than right and print the array.