if / else if / else, ternary? :andswitchwork as in C.for,while,do...whileloops.- Range-based for loops over any container:
for (int x : numbers).
C++ Conditions & Loops
if, switch, for, while and range-based for.
✍️ 2 exercises in this lessonKey Takeaways: C++ Conditions & Loops
Mastering C++ Conditions & Loops helps you write clean and reliable C++ code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
C++ Conditions & Loops Code Example
C++#include <iostream>
#include <vector>
int main() {
std::vector<int> marks = {72, 95, 58, 88};
for (int m : marks) {
if (m >= 85) std::cout << m << ": A\n";
else if (m >= 60) std::cout << m << ": B\n";
else std::cout << m << ": Fail\n";
}
int n = 1;
while (n < 50) n *= 3;
std::cout << "n = " << n << "\n";
return 0;
}
Output
72: B 95: A 58: Fail 88: A n = 81
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
C++ Conditions & Loops Practice Exercises
Check what you learned in “C++ Conditions & Loops”.
/ 2 solved
Fill in the blank
Loop over every element of a vector (range-based for).
for (int x numbers) { }
✓ Correct!
Not quite. Try again.
Multiple choice
Which loop is best for a known number of iterations?
✓ Correct!
Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services