Control Flow and Loops
Programs need to make decisions and repeat work. C++'s control-flow keywords work a lot like other C-family languages (JavaScript, C#, Java), so what you learn here will transfer directly.
#include <iostream>
int main() {
int xp = 45;
if (xp >= 50) {
std::cout << "Level up!" << std::endl;
} else {
std::cout << "Keep going, " << (50 - xp) << " XP to go." << std::endl;
}
for (int i = 1; i <= 5; i++) {
std::cout << "Lesson " << i << std::endl;
}
int count = 0;
while (count < 3) {
std::cout << "count = " << count << std::endl;
count++;
}
return 0;
}
The pieces
if/elsebranches on a boolean condition, the condition must always be wrapped in parentheses.for (init; condition; increment)runs the init once, then repeats: check condition, run the loop body, run the increment, check condition again, and so on. Best when you know how many times to loop.while (condition)keeps looping as long as the condition stays true, checked before every iteration, useful when you don't know the number of iterations ahead of time.
TIP
Forgetting to update the loop variable (like count++) is one of the most common beginner bugs, it creates an infinite loop that never becomes false.