Skip to main content

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​

OperatorMeaningExample
==Equal toa == b
!=Not equal toa != b
<Less thana < b
>Greater thana > b
<=Less than or equala <= b
>=Greater than or equala >= 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.

InputReturn
5positive
-3negative
0zero

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;
}
Don't forget 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.

InputReturn
1coffee
2tea
3water
anything elseunknown

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.

InputReturn
515
11
1055

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.

InputOutput
55 4 3 2 1
11

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 typeChecks conditionUse when
forBefore each iterationCount is known
whileBefore each iterationCount is unknown
do-whileAfter each iterationBody 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 linesReturn
-2 then 0 then 44
77

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
101 2 4 5 7 8
51 2 4

Exercises​

Activity: FizzBuzz

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.

πŸ“’ Solution