C++ Range-for
The break and continue page ended with thirty-nine lines on the screen, and the last one was 3, the final value that the early-exit for printed. This page starts from that screen, in the same file types.cpp, and the first box still holds the word pine. The earlier loops stay in the file. The array scores is already there with the values 4, 5, and 6. The new work walks that array with a range-for, so every element prints without a hand-written index. The screen grows to forty-two lines, and the last three are 4, then 5, then 6.
This page finishes the Control Flow module. You already printed scores[0] and scores[2] on earlier pages, and you already wrote counted for loops with an index. A range-for is the loop shape that says “for each element in this array” in one header. The colon sits between a new name and the array. On every pass, that name holds the current element, and the body can print it.
Programs walk lists all the time. A row of scores is printed one by one. A list of prices is checked one by one. Writing scores[0], then scores[1], then scores[2] by hand works for three boxes, but it does not scale when the length grows. A range-for keeps the walk in one place and reuses the body for every element.
A range-for starts with the keyword for and a header that is not the counted shape. The line for (int value : scores) shows that shape. On the left of the colon sits a type and a name: int value. On the right of the colon sits the array to walk: scores. There is no start counter, no upper-bound test, and no i++ in that header. The braces after the line hold the body. In this file the body prints the current element with std::cout << value << std::endl;.
On the first pass, value holds 4, the first element of scores, and the body prints 4. On the second pass, value holds 5, and the body prints 5. On the third pass, value holds 6, and the body prints 6. Then the walk ends, because every element has been visited. Three new lines appear: 4, then 5, then 6.
The name after the type is a choice. This file uses value, a clear name for “the element on this pass.” The same shape works with another name, as long as the body uses that same name. The type on the left must match the element type of the array. Here the elements are int, so the header uses int. The braces are required when the body has more than one statement, and this course always writes braces, even for one statement.
A counted for still fits when you need the index itself, such as printing the position next to the value. A range-for fits when you only need each element in order. Mixing the two shapes in one header is a mistake. Do not write for (int i = 0 : scores). The colon shape does not take a start and a step. Another common mistake is to put quotes around value on the print line, so the screen shows the word value three times instead of the numbers. The print line in this file has no quotes around value.
The array on the right must already exist. This page does not create a new array. It reuses scores, the same three boxes declared earlier in the file. Changing an element inside a plain int value copy does not change scores itself on this page. The teaching point here is reading and printing every element, not writing back into the array.
This page ends the loop tools in Control Flow and stops before the next module. The next page starts Functions, where you pack a piece of work under a name you can call. The range-for you have just written is the right shape when every element should run through the same body.
Type the file in this order, or add only the new lines if types.cpp is already on disk. After the for loop that uses continue and break, and before return 0;, add the range-for over scores with its braces and the print line for value. The file name on disk stays types.cpp. The checked file is below, and the new lines are that range-for statement and the print inside its braces.
#include <iostream>
#include <string>
int main()
{
// the word stays pine
std::string word = "pine";
int count = 2;
double ratio = 0.5;
bool ready = true;
double price = 7.9;
const int limit = 10;
int scores[3] = {4, 5, 6};
std::string other = "cone";
std::string joined = word + " " + other;
int total = 17;
int step = 3;
step += 4;
int score = 72;
int goal = 50;
bool wet = false;
std::string result;
int day = 3;
std::string name;
std::cout << word << std::endl;
std::cout << count << std::endl;
std::cout << ratio << std::endl;
std::cout << ready << std::endl;
std::cout << word.size() << std::endl;
std::cout << joined << std::endl;
std::cout << word[0] << std::endl;
std::cout << joined.find("cone") << std::endl;
std::cout << joined.substr(5, 4) << std::endl;
std::cout << count * 4 << std::endl;
std::cout << 7 / 2 << std::endl;
std::cout << 7.0 / 2 << std::endl;
std::cout << (count > 1) << std::endl;
std::cout << (count == 3) << std::endl;
std::cout << !ready << std::endl;
std::cout << static_cast<int>(price) << std::endl;
std::cout << static_cast<double>(count) / 4 << std::endl;
std::cout << static_cast<int>(ratio * 3) << std::endl;
std::cout << limit << std::endl;
std::cout << limit * count << std::endl;
std::cout << scores[0] << std::endl;
std::cout << scores[2] << std::endl;
std::cout << total % 5 << std::endl;
std::cout << step << std::endl;
std::cout << (score >= goal) << std::endl;
std::cout << (score < goal) << std::endl;
std::cout << ((score >= goal) && (count == 2)) << std::endl;
std::cout << ((score < goal) || wet) << std::endl;
if (score >= goal) {
result = "pass";
} else {
result = "retry";
}
std::cout << result << std::endl;
if (wet) {
std::cout << "wet" << std::endl;
}
switch (day) {
case 1:
name = "mon";
break;
case 2:
name = "tue";
break;
case 3:
name = "wed";
break;
default:
name = "other";
break;
}
std::cout << name << std::endl;
for (int i = 0; i < 3; i++) {
std::cout << i << std::endl;
}
int n = 3;
while (n > 0) {
std::cout << n << std::endl;
n--;
}
for (int k = 0; k < 5; k++) {
if (k == 2) {
continue;
}
if (k == 4) {
break;
}
std::cout << k << std::endl;
}
for (int value : scores) {
std::cout << value << std::endl;
}
return 0;
}
Rebuild with g++ -std=c++17 types.cpp -o types, then run ./types. If g++ is missing and clang++ is the compiler you installed, swap only the tool name: clang++ -std=c++17 types.cpp -o types. The screen shows forty-two lines. The first thirty-nine are the same as on the break and continue page. The last three are 4, then 5, then 6, the elements of scores in order.
Check the last three lines first. The range-for visited every element once, copied it into value, and printed that copy. The table gives each row its piece, so compare your run with it line by line. If the screen shows only thirty-nine lines, the range-for block is missing or sits after return 0;. If the last three lines are the word value, the print line has quotes around value. If only one new line appears, you may have printed scores[0] by hand instead of walking the array.
📊 The range-for and what it shows
| Piece | What the screen shows |
|---|---|
| First | 4, because the first element of scores is 4 and the first pass prints that value |
| Last | 6, because the walk visits every element, so the last printed value is 6 |
| Rule | a range-for copies each element into the name left of the colon |
| Screen | pine, 2, 0.5, 1, 4, pine cone, p, 5, cone, 8, 3, 3.5, 1, 0, 0, 7, 0.5, 1, 10, 20, 4, 6, 2, 7, 1, 0, 1, 0, pass, wed, 0, 1, 2, 3, 2, 1, 0, 1, 3, 4, 5, 6 |
Try one change at a time. Change the print line to std::cout << value * 2 << std::endl;, leave the header as it is, and rebuild. The last three lines become 8, then 10, then 12, because each element is doubled only for the print. Put the plain print of value back. Next, change the name from value to item in the header and on the print line, and rebuild. The last three lines stay 4, then 5, then 6, because only the name changed. Put value back. Each experiment changes one thing, so the screen shows exactly which part of the range-for caused the difference. Undo each change before the next one starts, so the file always returns to the checked version.
This page ends the Control Flow loop path and stops before Functions. The next page is functions, which packs a piece of work under a name you can call from main. The range-for you have just written is the right shape when every array element should run through the same body. You leave with forty-two lines on the screen, and the last one is 6. Count the lines before you leave. There are forty-two, and the last one is 6.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top