C++ Arrays
An array is a group of values of one type stored under one name. Each value has an index, and the first index is 0.
Reading one element
The array holds five scores. Index 2 reads the third score.
#include <iostream>
int main() {
int scores[5] = {85, 90, 78, 92, 88};
std::cout << scores[2] << std::endl;
return 0;
}Changing one element
Index 1 holds the second score. The new value replaces the old one.
#include <iostream>
int main() {
int scores[5] = {85, 90, 78, 92, 88};
scores[1] = 95;
std::cout << scores[1] << std::endl;
return 0;
}Printing all elements with a counting loop
The counter runs from 0 to 4. Each run prints the element at that index.
#include <iostream>
int main() {
int scores[5] = {85, 90, 78, 92, 88};
for (int i = 0; i < 5; i++) {
std::cout << scores[i] << std::endl;
}
return 0;
}Printing all elements with a range-for
The range-for takes each element in order. No index is named in the code.
#include <iostream>
int main() {
int scores[5] = {85, 90, 78, 92, 88};
for (int score : scores) {
std::cout << score << std::endl;
}
return 0;
}Counting the elements
sizeof(scores) gives the size of the whole array. sizeof(scores[0]) gives the size of one element.
#include <iostream>
int main() {
int scores[5] = {85, 90, 78, 92, 88};
std::cout << sizeof(scores) / sizeof(scores[0]) << std::endl;
return 0;
}Example
#include <iostream>
int main() {
int scores[5] = {70, 80, 90, 60, 100};
int total = 0;
for (int score : scores) {
std::cout << score << std::endl;
total += score;
}
std::cout << "Total: " << total << std::endl;
return 0;
}Key points
- An array stores values of one type under one name.
- An index in square brackets reads or changes one element.
- The first element sits at index 0.
- A counting for loop can visit each index in order.
- A range-for reads each element without naming an index.
- Dividing sizeof(scores) by sizeof(scores[0]) gives the element count.
In this example, the range-for visits each of the five scores. Each score prints on its own line, and the loop adds it to the total. The last line prints the total as 400.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C++ Compiler
Exercise
What does scores[0] read?