Repeat, and Repeat

C++ is known for very fast loops.


Count while repeating (for)

for (int i = 0; i < 10; ++i) {
    std::cout << i << "th time!" << std::endl;
}

Translation:

(Start i at 0; while i is less than 10; increase by 1) repeat {
    print the number and "th time!" and move to the next line;
}

Pull items from a bundle (range-based for)

std::vector<std::string> fruits = {"strawberry", "grape", "apple"};

for (std::string fruit : fruits) {
    std::cout << fruit << " sounds delicious!" << std::endl;
}

Translation:

Repeat by taking each item from fruits and naming it fruit {
    print fruit plus " sounds delicious!" and move to the next line;
}

Repeat while a condition is true (while)

int hp = 3;

while (hp > 0) {
    std::cout << "HP left: " << hp << std::endl;
    hp--; // subtract one
}

Translation:

While (hp is greater than 0) keep repeating {
    print "HP left: " plus hp and move to the next line;
    subtract 1 from hp;
}

Feel the lightning-fast repetition power of C++.