C++ · ОСНОВЫ · LESSON 20

Bottom line: command points

vector function and if · about 18 minutes

Learning with progressRead the summary for free. To save the work, log in to the account.
STEP 1

How it works.

Gather familiar details: vector stores glasses, the function counts the amount, if checks the target.

int total(vector<int> scores) {
    int sum = 0;
    for (int score : scores) sum += score;
    return sum;
}
The path of glasses
vectornumbertotalsumifgoal

✦ Check the amount: if you scored enough, show the message of victory.

STEP 2

Try to understand.

Check the amount: if you scored enough, show the message of victory.

vector<int> scores = {2, 3, 4};
if (total(scores) >= 8) {
    cout << "Победа" << endl;
}

✦ Compare this to the first one. Then do the cool job yourself.

IN-CLASS PRACTICE

Type the code yourself

Manually type the program from the sample. So you'll remember commands and brackets.

#include <iostream>
#include <vector>
using namespace std;

int total(vector<int> scores) {
    int sum = 0;
    for (int score : scores) sum += score;
    return sum;
}

int main() {
    vector<int> scores = {2, 3, 4};
    if (total(scores) >= 8) {
        cout << "Победа" << endl;
    }
    return 0;
}
Open the editor for class work
HOMEWORK

Solve it yourself

Создай функцию total для vector<int>: сложи все значения циклом и верни сумму. Для {1, 2, 5} выведи «Готово», если сумма не меньше 8.

The answer is hidden. Use similar examples from the lesson notes.

Opening up your homework