Skip to content

Arrays and Strings

Programming C++ Difficulty 1/5

Beginning of the lesson

Arrays and Strings

Store many values in a row, and work with text

Big Idea: Sometimes you need to keep many values, not just one. An array is a row of boxes that all hold the same type of value. A string is a special kind of sequence made of characters — it is how C++ keeps text.
By the end you will be able to:
  • 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::string and 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 indices 0, 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:

values 9008511002703954 indices (start at 0)
An array of 5 scores. Index 0 is the first box, index 4 is the last.

scores[0] is 90 and scores[4] is 95. There is no scores[5] — that box does not exist!

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers