New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› C++› Conditions and Loops

Conditions and Loops

💻 C++

Control program flow with if, switch, for and while.

Lesson 3 of 9 Tutorial
0 of 9 completed

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

  1. Print the grade for a score.
  2. Use switch to print a day name from a number.
  3. 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.
C++ exercise-1.txt
Expected Output
Numbers with Fizz, Buzz and FizzBuzz in the right places.

Lesson Nav

Lesson sections