Control Flow
Range For
A range-based for loop visits each value in a collection.
Range For
range_for.cpp
#include <iostream>
#include <string>
int main() {
int threshold = ;
int values[4] = {3, 5, 7, 9};
int count = 0;
for (int value : values) {
if (value >= threshold) {
count++;
}
}
std::cout << "threshold=" << threshold << std::endl;
std::cout << "count=" << count << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
int threshold = ;
int values[4] = {3, 5, 7, 9};
int count = 0;
for (int value : values) {
if (value >= threshold) {
count++;
}
}
std::cout << "threshold=" << threshold << std::endl;
std::cout << "count=" << count << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
int threshold = ;
int values[4] = {3, 5, 7, 9};
int count = 0;
for (int value : values) {
if (value >= threshold) {
count++;
}
}
std::cout << "threshold=" << threshold << std::endl;
std::cout << "count=" << count << std::endl;
return 0;
}
range-based for
Use `for (int value : values)` when the loop needs each element but not its index.