← C++ from Scratch Lesson 22 of 62 · 10 XP

Arrays

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

An array is several values of the same type in a row in memory:

int scores[5] = {10, 20, 30, 40, 50};
scores[0];              // 10 — numbering starts from zero
scores[4] = 99;         // the last item
int n = sizeof(scores) / sizeof(scores[0]);   // 5 — the length of the array

std::array<int, 5> a = {1, 2, 3, 4, 5};      // #include <array> — the same, but it knows its size: a.size()
  • the size of an ordinary array is a constant known at compile time;
  • going out of bounds (scores[5]) is undefined behaviour: C++ doesn't check the index, and the program may silently corrupt neighbouring data. std::array::at(i) does check, but it's better simply not to go out of bounds;
  • when the size is known only at run time, people use std::vector (module 7).

Task. Read exactly 5 integers into an array. Print them in reverse order separated by spaces, then the largest one.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.