Loading
0x20Lesson 3 of 9

Control flow with conditions and loops

Branch on conditions and repeat work with familiar control structures.

16 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Write if statements, for loops, and while loops with explicit blocks.

Use if and else to choose a path, and loops to repeat work. C++ conditions use boolean expressions; comparisons such as == produce a bool. A for loop is handy when the update step is clear, while while repeats as long as its condition remains true. Braces make the body explicit and reduce accidental control-flow mistakes.

main.cpp · C++20
1#include <iostream>
2
3int main() {
4    for (int n = 1; n <= 3; ++n) {
5        if (n % 2 == 0) {
6            std::cout << n << " is even\n";
7        } else {
8            std::cout << n << " is odd\n";
9        }
10    }
11}
Output
1 is odd
2 is even
3 is odd

++n increments before producing its value; for a built-in integer in this loop, n++ would also work. Use == to compare and = to assign. An accidental assignment in a condition can compile and change the program’s behavior.

Key takeaways

  • Use branches for decisions and loops for repetition.

  • Keep assignment = distinct from comparison ==.

  • Make loop bounds and termination conditions clear.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write C++

Write C++20 in the editor and run it against sample input. GCC 14 compiles the code through Compiler Explorer, a free public service; your source and test input are sent there.

Exercise 1

Sum from one to n

+25 XP

Read an integer n and print the sum of all integers from 1 through n as Sum: N. Assume n is between 1 and 1000.

  • Sum to 5
  • Sum to 1
main.c
Loading editor…

Your code is compiled as C++20 with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Did you like the lesson? 😆👍
Consider a donation to support our work: