Control flow and week 2 review
So far your programs run statements one after another. Control flow lets the program decide what to do (conditionals) and repeat actions (loops). With these two ideas, plus what you already know about variables and input, you can solve real problems. In this lesson you meet if, switch, while, do-while and for, and we close the week with a quiz.
Conditionals: if, else and switch
if (condition) runs its block only if the condition is true; else if chains alternatives and else catches the rest. Always use braces, even for a single statement: it avoids mistakes when you add lines later. When you compare one integer or char variable with several constant values, switch is clearer. Each case must end with break, or execution 'falls through' to the next case; this is a classic source of bugs. Since C++17 you can also declare a variable inside the if: if (int r = n % 3; r == 0) {...}, and its scope is limited to that if.
#include <iostream>
int main() {
int score{73};
if (score >= 90) {
std::cout << "Excellent\n";
} else if (score >= 70) {
std::cout << "Good\n";
} else {
std::cout << "Needs practice\n";
}
int day{3};
switch (day) {
case 1:
std::cout << "Monday\n";
break;
case 2:
std::cout << "Tuesday\n";
break;
case 3:
std::cout << "Wednesday\n";
break;
default:
std::cout << "Another day\n";
break;
}
return 0;
}Loops: while, do-while and for
while (condition) repeats as long as the condition is true and checks it before each round, so it may never run. do { ... } while (condition); checks at the end, so the body runs at least once; it is ideal for menus. for (init; condition; step) packs the three parts of a counter into one line and is the natural choice when you know how many rounds you will do. Inside any loop, break leaves it and continue jumps to the next round. Beware of infinite loops: if the variable in the condition never changes, the program never ends (interrupt it with Ctrl+C).
#include <iostream>
int main() {
// for: sum of 1..10
int sum{0};
for (int i = 1; i <= 10; ++i) {
sum += i;
}
std::cout << "sum = " << sum << '\n';
// while with continue: print odd numbers below 10
int n{0};
while (n < 10) {
++n;
if (n % 2 == 0) {
continue;
}
std::cout << n << ' ';
}
std::cout << '\n';
// do-while: runs at least once
int tries{0};
do {
++tries;
} while (tries < 3);
std::cout << "tries = " << tries << '\n';
return 0;
}A review program
The following program combines input, validation, loops and conditionals: a number guessing game. Read each line and make sure you understand why each part is there; if something is unclear, run it with different values. Notice how the loop condition uses logical operators and how invalid input is handled.
#include <iostream>
#include <limits>
int main() {
constexpr int kSecret = 42;
constexpr int kMaxTries = 5;
int tries{0};
bool won{false};
while (tries < kMaxTries && !won) {
int guess{};
std::cout << "Guess (" << kMaxTries - tries << " left): ";
if (!(std::cin >> guess)) {
if (std::cin.eof()) {
break;
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Numbers only!\n";
continue; // invalid input does not use a try
}
++tries;
if (guess == kSecret) {
won = true;
} else if (guess < kSecret) {
std::cout << "Too low\n";
} else {
std::cout << "Too high\n";
}
}
std::cout << (won ? "You won!\n" : "Game over\n");
return 0;
}Two classic review mistakes. The first: writing if (x = 5) with a single equals sign, which assigns 5 to x and is always true, instead of comparing with ==. Compiler warnings (-Wall) usually point it out, so always enable them. The second: forgetting the break at the end of a case in a switch, so execution "falls through" to the next case. If you do it on purpose, document it with the [[fallthrough]] attribute; for everything else, end each case with break or return.
Teste dein Wissen
Frage 1 von 6What does 17 % 5 give?
✎ Meine Notizen
Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen