Arrays and Strings
Store many values in a row, and work with text
- make a fixed-size array and read its elements by index,
- loop over an array to add up or check every value,
- store text in a
std::stringand use its common methods.
1. What is an array?
An array is a group of values of the same type, stored next to each other in memory. Think of an egg carton: it has a fixed number of cups in a row, and each cup holds one egg. An array cup is called an element.
Two important rules:
- Fixed size. When you make a plain array you choose how many boxes it has, and that number does not change.
- Zero-based index. The boxes are numbered starting at
0. So an array of 5 elements uses indices0, 1, 2, 3, 4— the last index is one less than the size.
2. Making an array and reading elements
You declare an array by writing the type, a name, and the size in square brackets. You can fill it with values inside { }. You read a single element with its index in square brackets.
#include <iostream>
using namespace std;
int main() {
int scores[5] = {90, 85, 100, 70, 95};
cout << scores[0] << endl; // first element (index 0)
cout << scores[4] << endl; // last element (index 4)
return 0;
}
// Output:
// 90
// 95
Here is how those five numbers sit in memory. The blue boxes are the values; the orange numbers underneath are the indices you use to reach them:
scores[0] is 90 and scores[4] is 95. There is no scores[5] — that box does not exist!