C++ fundamentals · Lesson 4 of 21
Conditions: if and switch
if/else, logical operators, switch and the ternary operator.
9 minutes2 games
if runs code when a condition is true, else if tries another, and else covers the rest. The condition goes in brackets and the code in { }.
C++
#include <iostream>
int main() {
int score = 76;
bool submittedProject = true;
if (score >= 90) {
std::cout << "Excellent\n";
} else if (score >= 70 && submittedProject) {
std::cout << "Passed with project\n";
} else if (score >= 70) {
std::cout << "Passed\n";
} else {
std::cout << "Try again\n";
}
return 0;
}| Operator | Meaning |
|---|---|
a == b | equals |
a != b | not equal |
a && b | and (both true) |
a || b | or (at least one) |
!a | not |
c ? x : y | x if c is true, else y |
switch
C++
#include <iostream>
int main() {
char level = 'B';
switch (level) {
case 'A':
std::cout << "Advanced\n";
break;
case 'B':
case 'C':
std::cout << "Intermediate\n";
break;
default:
std::cout << "Beginner\n";
}
int xp = 120;
std::cout << (xp >= 100 ? "level up" : "keep going") << "\n";
return 0;
}Spot the bug
With day = 6 the program prints two lines instead of one. Where's the problem?
Exercise
You have int n = 15. Print FizzBuzz if it divides by both 3 and 5, Fizz for 3 only, Buzz for 5 only, or the number itself.
Expected output: FizzBuzz
C++
#include <iostream>
int main() {
int n = 15;
return 0;
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.