Small Steps VI — Growing into C++

Write C++ without Small

Write C++ without Small

Explore one topic in small steps. Try the examples one at a time and take a break whenever you need. Choose how many extra exercises you want to try.

Greeting without Small

What you will learn

Using only the standard tools you have learned lets you do the same work without Small.

Try it

Example · example1.cpp
#include <iostream>
#include <string>

int main()
{
    std::string name;

    std::cout << "Name: ";
    std::getline(std::cin, name);

    std::cout << "Hello, " << name << "\n";

    return 0;
}

Use main instead of small_main, std::string instead of String, getline instead of input, and cout instead of print. Entering Alex produces Hello, Alex.

Because no Small features are used, small.h, initialize_small, and shutdown_small are unnecessary too.

Using 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 · beyond_2_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

Write a main program that adds all values in a std::vector<int> and prints the sum with std::cout, using no Small API.

Exercise starter · exercise1_starter.cpp
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> numbers = {10, 20, 30};
    int total = 0;

    // sum and print using only standard C++.

    return 0;
}

Hint

Write #include <iostream> and #include <vector> yourself.

show solution
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> numbers = {10, 20, 30};
    int total = 0;

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

    std::cout << total << "\n";

    return 0;
}
Try More (Optional)

Exercise

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

Exercise starter · beyond_2_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 →