C++ Loops
Besides for, while and do...while, C++ has the range-based for loop that walks through a container.
ExampleC++
#include <iostream>
#include <vector>
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) cout << "for " << i << endl;
int n = 3;
while (n > 0) {
cout << "while " << n << endl;
n--;
}
vector<string> cars = {"Volvo", "BMW", "Ford"};
for (const string &car : cars) {
cout << car << endl;
}
return 0;
}Output
for 1 for 2 for 3 while 3 while 2 while 1 Volvo BMW Ford
Quick check
Which loop walks through every element of a container?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.