C++ for Loops
The switch page ended with thirty lines on the screen, and the last one was wed, the name that case 3: stored when day held 3. This page starts from that screen, in the same file types.cpp, and the first box still holds the word pine. Every line so far has printed a value that the code computed once. From this page on, the program can repeat a block of code, so the screen grows to thirty-three lines in a new way.
This page continues the Control Flow module. The choice tools were if, else, and switch. The loop tools begin here. A loop runs the same block again and again while a test stays true. The first of them is for, which keeps a counter, checks a test before each pass, and updates the counter after each pass. The file keeps its name, and the new work adds one loop at the end of main.
Programs repeat work all the time. A list of scores is printed one by one. A countdown ticks from a start value down to zero. A menu redraws until the user picks a choice. Each of those jobs needs the same writing line more than once, with a value that changes on every pass. Writing three separate print lines by hand works for a tiny demo, but it does not scale when the count grows. A for loop puts the count in one place and reuses the body.
A for statement starts with the keyword for and three jobs inside parentheses, separated by semicolons. The line for (int i = 0; i < 3; i++) shows that shape. The first job is the start: int i = 0 makes a whole-number box named i and stores 0 in it. The second job is the test: i < 3 asks whether the body should run again. The third job is the step: i++ adds one to i after the body finishes. The braces after the for line hold the body, and the body in this file prints the current value of i.
The start runs once, before the first test. The test runs before every pass, including the first. When the test is true, the body runs, then the step runs, then the test runs again. When the test is false, the loop ends, and the program continues with the line after the closing brace. In this file, i starts at 0. The test i < 3 is true, so the body prints 0. The step stores 1. The test is still true, so the body prints 1. The step stores 2. The test is still true, so the body prints 2. The step stores 3. Now i < 3 is false, so the loop stops. Three new lines appear on the screen: 0, then 1, then 2.
The counter name is a choice. This file uses i, a short name that is common for a loop index. The same shape works with any name, as long as the start, the test, and the step all talk about that name. The braces are required when the body has more than one statement, and this course always writes braces, even for one statement, so the body stays clear when a second line is added later.
The three jobs must stay in that order. The start is not a print. The test is not a step. The step is not a second start. A common mistake is to write the print line outside the braces, so the loop runs three times with an empty body and then prints once. Another common mistake is to put quotes around i on the print line, so the screen shows the letter i three times instead of the numbers. The print line in this file is std::cout << i << std::endl;, with no quotes around i, so the number appears.
The step i++ means the same thing as i = i + 1 for this page. Either form adds one to the counter after the body. The form i++ is short and common in C++ loops. The test uses <, not <=, so the body runs for 0, 1, and 2, and stops when i becomes 3. If the test were i <= 3, the body would also run when i held 3, and a fourth line would appear. The upper bound in the test is the value that ends the loop, not a value that the body prints when the bound is exclusive.
A for loop is the right tool when the number of passes is known before the loop starts. When the stop depends on a value that arrives later, such as a word the user types, a different loop fits better. This page stops before that tool. The next page names it once at the end.
Type the file in this order, or add only the new lines if types.cpp is already on disk. After the line that prints name, and before return 0;, add the for loop with its braces and the print line for i. The file name on disk stays types.cpp. The checked file is below, and the new lines are the 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;
}
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 thirty-three lines. The first thirty are the same as on the switch page. The last three are 0, then 1, then 2, the values of i on each pass.
Check the last three lines first. The loop started with i equal to 0, printed that value, stepped to 1, printed again, stepped to 2, printed again, and stopped when i became 3. The table gives each row its piece, so compare your run with it line by line. If the screen shows only thirty lines, the for block is missing or sits after return 0;. If the last three lines are the letter i, the print line has quotes around i.
📊 The for loop and what it shows
| Piece | What the screen shows |
|---|---|
| First | 0, because i starts at 0 and the first pass prints that value |
| Last | 2, because the body runs while i is less than 3, so the last printed value is 2 |
| Rule | a for runs start once, then test, body, and step while the test stays true |
| 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 |
Try one change at a time. Change i < 3 to i < 5 inside the for line, and rebuild. The last five lines become 0, 1, 2, 3, and 4, because the body keeps running until i reaches 5. Put the 3 back. Next, change the start from int i = 0 to int i = 1, leave the test as i < 3, and rebuild. The new lines become 1 and 2 only, because the first pass starts at 1. Put the 0 back. Each experiment changes one thing, so the screen shows exactly which part of the for line caused the difference. Undo each change before the next one starts, so the file always returns to the checked version.
This page ends the first loop tool and stops before the next one. The next page is while, which repeats a block while a condition stays true without a fixed start and step in the same parentheses. The for you have just written is the right shape when the count is known up front. You leave with thirty-three lines on the screen, and the last one is 2. Count the lines before you leave. There are thirty-three, and the last one is 2.
🧠 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