🚀 Alguni Start learning

Unit 2: Choices, Loops & Vectors

Lists that can grow.

Unit 2 of 8 in C++ for kids. Its 4 lessons are If / Else, Loops, Vectors and Game Builder — below is everything each one explains, and a question or two from it to try.

Every sample on this page was compiled and run with g++ before it shipped, and prints exactly what it says it prints.

This unit is free for ever, because the first two units of every track are. Try it in the app.

🔀 If / Else

Exactly like C

Nothing new here — braces, and the question in round brackets. The only nicety is that the condition can be a real bool.

C++

int age = 7;
if (age > 10) {
    cout << "Big kid" << endl;
} else {
    cout << "Little kid" << endl;
}

It prints

Little kid

Try it yourself

What does this print?

C++

bool raining = false;
if (raining) {
    cout << "Take a coat" << endl;
} else {
    cout << "Sunny!" << endl;
}

What does this print?

C++

int score = 55;
if (score >= 90) {
    cout << "Gold" << endl;
} else if (score >= 50) {
    cout << "Silver" << endl;
} else {
    cout << "Bronze" << endl;
}

Answer them in the app

🔁 Loops

The same three-part loop

Start, keep-going test, step — just as in C and JavaScript.

C++

for (int i = 0; i < 3; i++) {
    cout << i << endl;
}

It prints

0
1
2

Try it yourself

What is the last number printed?

C++

for (int i = 1; i <= 5; i++) {
    cout << i << endl;
}

What does this print?

C++

int total = 0;
for (int i = 1; i <= 4; i++) {
    total = total + i;
}
cout << total << endl;

Answer them in the app

📋 Vectors

Arrays that can grow

A C array was stuck at the size you chose. A C++ vector can grow whenever you like with .push_back(), and it always knows its own .size().

C++

#include <vector>

vector<int> nums = {4, 8};
nums.push_back(15);
cout << nums.size() << endl;
cout << nums[2] << endl;

It prints

3
15

Walking through a vector

A range-for reads much better than counting by hand: "for each n in nums".

C++

vector<int> nums = {4, 8, 15};
for (int n : nums) {
    cout << n << endl;
}

It prints

4
8
15

Try it yourself

What does vector<int> mean?

  • A vector of any type
  • A growable list where every item is an int
  • Exactly one int
  • A list of exactly int-many things

What does this print?

C++

vector<int> nums = {4, 8, 15};
cout << nums.size() << endl;

Answer them in the app

🏆 Game Builder

Try it yourself

What does this print?

C++

vector<string> pets = {"cat", "dog"};
pets.push_back("fish");
cout << pets[2] << endl;

What does this print?

C++

vector<int> scores = {10, 20, 30};
int best = 0;
for (int s : scores) {
    if (s > best) {
        best = s;
    }
}
cout << best << endl;

Answer them in the app