Chapter 2a - Conditionals & Loops
If / Elseβ
Use if to run code only when a condition is true. else if and else handle alternative cases.
int score = 75;
if (score >= 90) {
cout << "Grade: A" << endl;
} else if (score >= 80) {
cout << "Grade: B" << endl;
} else if (score >= 70) {
cout << "Grade: C" << endl;
} else {
cout << "Grade: F" << endl;
}
Comparison Operatorsβ
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
< | Less than | a < b |
> | Greater than | a > b |
<= | Less than or equal | a <= b |
>= | Greater than or equal | a >= b |
= vs === assigns a value. == compares two values. Mixing them up is one of the most common C++ bugs.
Logical Operatorsβ
Combine multiple conditions with && (AND), || (OR), ! (NOT).
int age = 20;
bool hasId = true;
if (age >= 18 && hasId) {
cout << "Access granted." << endl;
}
bool isWeekend = false;
bool isHoliday = true;
if (isWeekend || isHoliday) {
cout << "No school today!" << endl;
}
π§ͺ Try conditionals
Press Run, then type a number and press Enter.
Challenge: sign of a numberβ
Finish signWord so it returns "positive", "negative", or "zero". Use if / else if / else, not switch.
| Input | Return |
|---|---|
5 | positive |
-3 | negative |
0 | zero |
Switch Statementβ
switch is a cleaner alternative to long if/else if chains when checking a single variable against exact values.
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
default:
cout << "Another day" << endl;
break;
}
break!Without break, execution "falls through" to the next case. This is almost always a bug unless intentional.
π§ͺ Try switch
Enter a day number 1β7.
Challenge: drink menuβ
Finish drinkName so it returns a string from an integer order. Use switch, not if. A hidden main reads one number and prints your return value.
| Input | Return |
|---|---|
1 | coffee |
2 | tea |
3 | water |
| anything else | unknown |
For Loopβ
Use a for loop when you know how many times to repeat.
// Syntax: for (init; condition; update)
for (int i = 0; i < 5; i++) {
cout << "i = " << i << endl;
}
i = 0
i = 1
i = 2
i = 3
i = 4
π§ͺ Loop examples
Challenge: sum with forβ
Finish sumTo so it returns 1 + 2 + β¦ + n. Use a for loop, not while.
| Input | Return |
|---|---|
5 | 15 |
1 | 1 |
10 | 55 |
Nested For Loopsβ
Loops can be placed inside other loops. The inner loop completes fully for each step of the outer loop.
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
cout << row << "x" << col << "=" << row * col << " ";
}
cout << endl;
}
1x1=1 1x2=2 1x3=3
2x1=2 2x2=4 2x3=6
3x1=3 3x2=6 3x3=9
π§ͺ Nested loops
While Loopβ
Use while when you want to repeat as long as a condition holds, and you don't know the count upfront.
int count = 0;
while (count < 5) {
cout << "count = " << count << endl;
count++;
}
π§ͺ While loop with user input
Guess until you get 42. Type a number and press Enter after each prompt.
Challenge: countdown with whileβ
Finish countDown so it prints n down to 1, separated by spaces. Use while, not for.
| Input | Output |
|---|---|
5 | 5 4 3 2 1 |
1 | 1 |
Do-While Loopβ
do-while always runs the body at least once, then checks the condition.
int n;
do {
cout << "Enter a positive number: ";
cin >> n;
} while (n <= 0);
cout << "You entered: " << n << endl;
| Loop type | Checks condition | Use when |
|---|---|---|
for | Before each iteration | Count is known |
while | Before each iteration | Count is unknown |
do-while | After each iteration | Body must run at least once |
π§ͺ Try do-while
Enter a non-positive number first (like -3), then a positive one.
Challenge: first positive with do-whileβ
Finish firstPositive so it reads integers until one is greater than 0, then returns that value. Use do / while. Hidden tests send several lines of input.
| Input lines | Return |
|---|---|
-2 then 0 then 4 | 4 |
7 | 7 |
Break and Continueβ
break exits the loop immediately. continue skips the rest of the current iteration and moves to the next.
// Skip multiples of 3, stop at 10
for (int i = 1; i <= 15; i++) {
if (i == 10) break;
if (i % 3 == 0) continue;
cout << i << " ";
}
// Output: 1 2 4 5 7 8
π§ͺ Break and continue
Challenge: skip threes, then breakβ
Finish printSkipThrees. Loop i from 1 to 20. break when i equals limit. continue when i is a multiple of 3. Print the other numbers with a space after each.
Input (limit) | Output |
|---|---|
10 | 1 2 4 5 7 8 |
5 | 1 2 4 |
Exercisesβ
Print the numbers 1 to 100. For multiples of 3 print "Fizz", for multiples of 5 print "Buzz", for multiples of both print "FizzBuzz".
1
2
Fizz
4
Buzz
Fizz
7
...
π‘ Hint
Check i % 3 == 0 && i % 5 == 0 first (before checking each individually), or the combined case will never be reached.