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
#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num;

if (num > 0) {
cout << num << " is positive." << endl;
} else if (num < 0) {
cout << num << " is negative." << endl;
} else {
cout << "The number is zero." << endl;
}

return 0;
}

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.


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
#include <iostream>
using namespace std;

int main() {
// Print even numbers from 2 to 10
for (int i = 2; i <= 10; i += 2) {
cout << i << " ";
}
cout << endl;

// Count down
for (int i = 5; i >= 1; i--) {
cout << i << "... ";
}
cout << "Blast off!" << endl;

return 0;
}

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

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
#include <iostream>
using namespace std;

int main() {
int guess;
int secret = 42;

while (guess != secret) {
cout << "Guess the number: ";
cin >> guess;

if (guess < secret) {
cout << "Too low!" << endl;
} else if (guess > secret) {
cout << "Too high!" << endl;
}
}

cout << "Correct! The number was " << secret << "." << endl;
return 0;
}

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

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

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
#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0) {
cout << "FizzBuzz" << endl;
} else if (i % 3 == 0) {
cout << "Fizz" << endl;
} else if (i % 5 == 0) {
cout << "Buzz" << endl;
} else {
cout << i << endl;
}
}
return 0;
}
Activity: Multiplication Table

Ask the user for a number and print its multiplication table from 1 to 10.

Expected output for input 7:

7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70
πŸ“’ Solution
#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter a number: ";
cin >> n;

for (int i = 1; i <= 10; i++) {
cout << n << " x " << i << " = " << n * i << endl;
}

return 0;
}
Activity: Sum of Digits

Read a positive integer from the user and print the sum of its digits.

Example: input 1234 β†’ output Sum of digits: 10

πŸ’‘ Hint

Use % 10 to get the last digit, then /= 10 to remove it. Loop until the number is 0.

πŸ“’ Solution
#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a positive integer: ";
cin >> num;

int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}

cout << "Sum of digits: " << sum << endl;
return 0;
}