Many values, one name
Suppose you need the marks of 5 students. Five separate variables (mark1, mark2, ...) would get messy. An array holds many values of the same type under one name:
#include <iostream>
using namespace std;
int main() {
int marks[5] = {72, 85, 90, 64, 78};
cout << "First mark: " << marks[0] << "\n";
cout << "Third mark: " << marks[2] << "\n";
cout << "Last mark: " << marks[4] << "\n";
return 0;
}Output
First mark: 72 Third mark: 90 Last mark: 78
Think of it like this: An array is like a row of numbered lockers. All the lockers share one name (
marks), and each has a number on its door (the index).
Remember: Indexes start at 0, not 1! An array of 5 items has indexes 0, 1, 2, 3 and 4.
Changing an item
#include <iostream>
using namespace std;
int main() {
int marks[5] = {72, 85, 90, 64, 78};
marks[3] = 70; // change the 4th mark
marks[0] += 5; // add 5 to the first mark
cout << marks[0] << " " << marks[3] << "\n";
return 0;
}Output
77 70
Looping over an array
A for loop from 0 up to (but not including) the size visits every item:
#include <iostream>
using namespace std;
int main() {
const int SIZE = 5;
int marks[SIZE] = {72, 85, 90, 64, 78};
int total = 0;
for (int i = 0; i < SIZE; i++) {
cout << "Student " << i + 1 << ": " << marks[i] << "\n";
total += marks[i];
}
cout << "Average: " << total / static_cast<double>(SIZE) << "\n";
return 0;
}Output
Student 1: 72 Student 2: 85 Student 3: 90 Student 4: 64 Student 5: 78 Average: 77.8
Common mistake: Going past the end.
marks[5]in a 5-item array is out of bounds. C++ does not stop you – it reads or overwrites whatever memory is there. This bug (a buffer overflow) is behind many famous security attacks.
Tip: Arrays have a fixed size that can never change. For lists that grow and shrink, use a
vector(next lesson).