
Would you make 30 variables for 30 test scores? No. An array is a row of numbered boxes: one name, many slots.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
int score[5] = {70, 85, 90, 60, 100};
cout << score[0] << endl; // 70 (first)
cout << score[4] << endl; // 100 (last)
score[1] = 88; // change one slot
for (int i = 0; i < 5; i++) {
cout << score[i] << " ";
}
cout << endl;
return 0;
}> what you see
70 100 70 88 90 60 100
//LINE BY LINE
Watch it run
int score[5] makes five slots, numbered 0 through 4.
Counting starts at zero
An array of 5 elements has indexes 0, 1, 2, 3, 4 — there is no index 5.
int a[5] = {10, 20, 30, 40, 50};
// ↑0 ↑1 ↑2 ↑3 ↑4
cout << a[0] << endl; // 10 — эхний
cout << a[4] << endl; // 50 — сүүлийн> what you see
10 50
Reading a[5] gives no error in C++ — you get junk memory, or a crash. Staying inside the bounds is your job.
Ways to fill an array
int a[5] = {1, 2, 3, 4, 5}; // бүгдийг нь шууд
int b[5] = {0}; // бүгд тэг
int c[5]; // хоосон — дотор нь хог
int d[] = {1, 2, 3}; // хэмжээг өөрөө тоолно (3)An array's size must be a constant. int n; cin >> n; int a[n]; is not standard C++ — use a vector instead.