Small Steps VI — Growing into C++

Using the same procedures in standard C++

Use the same procedures in standard C++.

What you will learn

Even when tool notation changes, storing values, looping, and accumulating a sum remain the same procedures.

Try it

Example · example2.cpp
#include <iostream>
#include <vector>

int sum(const std::vector<int>& numbers)
{
    int total = 0;

    for (int value : numbers)
        total = total + value;

    return total;
}

int main()
{
    std::vector<int> numbers = {3, 7, 2, 9, 4};

    std::cout << "Sum: " << sum(numbers) << "\n";

    return 0;
}

Add the vector's values with a range-based for and print the value returned by a function with cout. The result is Sum: 25.

Variables, conditions, loops, and functions learned so far all work in ordinary C++ too. Keep learning new tools as you need them for things you want to make.

Exercise

Create greet taking a const std::string&, printing Hello, name! with std::cout, and call it from main.

Exercise starter · exercise2_starter.cpp
#include <iostream>
#include <string>

// write greet here.

int main()
{
    std::string name = "Alex";

    // Call greet.

    return 0;
}

Hint

You need #include <iostream> and #include <string>.

show solution
#include <iostream>
#include <string>

void greet(const std::string& name)
{
    std::cout << "Hello, " << name << "!\n";
}

int main()
{
    std::string name = "Alex";

    greet(name);

    return 0;
}
← Previous lessonNext lesson →