Beginner level · Module 2: Control Flow and Functions in C++ · Lesson 1 of 3
Decisions and Loops
Control what runs with if/else and switch, and repeat work with for, while and do-while loops.
In this lesson you will
- Write conditions with comparison and logical operators
- Choose the right loop for counted and conditional repetition
Key concepts
if / else if / elseswitchfor and whileinfinite loop
The lesson
Conditions are bool expressions: score >= 50, age < 18 && hasConsent. if / else if / else runs the first true branch. switch compares one integer or character against fixed cases; remember break at the end of each case, or execution falls through to the next.
A for loop suits counted repetition: for (int i = 0; i < 10; ++i). A while loop repeats while a condition holds, such as reading values until the user enters 0. A do-while loop runs at least once, which suits menus.
When reading numbers in a loop, check that the read succeeded: while (std::cin >> value) stops cleanly at the end of input or when non-numeric text is typed.
Step by step
- Write a grade classifier with if / else if.
- Rewrite a menu choice with switch, including break statements.
- Read numbers until 0 and print their sum and count.
- Make a do-while menu that repeats until Exit is chosen.
Practice activity
Write a till loop that reads prices until 0 and prints the item count, total and average.
Expected result: Prices 2000, 3500 and 1500 followed by 0 give 3 items, total 7000 and average 2333.33.
Check your understanding
-
What happens if a switch case has no break?
Show answer
Execution falls through into the next case.
-
Which loop always runs at least once?
Show answer
do-while.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.