C++ conditions and loops work like most languages, with a few details that matter for correctness.
By the end of this lesson you can:
- Write if and else-if chains.
- Use switch with break.
- Write for and while loops.
if Statements
Conditions are numeric or boolean. Be explicit rather than relying on implicit conversions.
int score = 72;
if (score >= 70) {
std::cout << "A\n";
} else if (score >= 60) {
std::cout << "B\n";
} else {
std::cout << "Keep working\n";
}switch
A switch compares one value against cases. Without break, execution falls through to the next case, which is rarely intended.
switch (grade) {
case 'A':
std::cout << "Excellent\n";
break;
case 'B':
std::cout << "Good\n";
break;
default:
std::cout << "Keep going\n";
}Loops
Use a for loop when the number of iterations is known and a while loop when it depends on a condition.
for (int i = 1; i <= 12; i++) {
std::cout << "7 x " << i << " = " << 7 * i << "\n";
}
int countdown = 3;
while (countdown > 0) {
std::cout << countdown << "\n";
countdown--;
}Warning A for loop that changes its index inside the body is hard to reason about. Keep the update in the loop header.
Practice
- Print the grade for a score.
- Use switch to print a day name from a number.
- Print all even numbers from 1 to 20.
Hands-on exercise
Print the numbers 1 to 30.
For multiples of 3 print Fizz, for multiples of 5 print Buzz, and for multiples of both print FizzBuzz.
Recap
Conditions choose branches, switch compares one value and loops repeat work. Watch for missing break statements.
Example
int score = 72;
if (score >= 70) {
std::cout << "A
";
} else if (score >= 60) {
std::cout << "B
";
} else {
std::cout << "Keep working
";
}
Exercises
Exercise 1. Fizz and Buzz
Easy
Print the numbers 1 to 30.
For multiples of 3 print Fizz, for multiples of 5 print Buzz, and for multiples of both print FizzBuzz.
For multiples of 3 print Fizz, for multiples of 5 print Buzz, and for multiples of both print FizzBuzz.
C++
exercise-1.txt
Output
Expected Output
Numbers with Fizz, Buzz and FizzBuzz in the right places.
Lesson Nav
Course contents
C++ Course
0/9 lessons completed
- 1 Your First C++ Program Tutorial
- 2 Variables, Types and Input Tutorial
- 3 Conditions and Loops Tutorial
- 4 Functions and Parameters Tutorial
- 5 Arrays and Vectors Tutorial
- 6 Pointers and References Tutorial
- 7 Classes and Objects Tutorial
- 8 The STL: Containers and Algorithms Tutorial
- 9 Project: A Console Grade Book Project
Exercises
Exercise 1 Fizz and Buzz