capypad
0 day streak
cpp / beginner
Snippet

Making Decisions with if and else

Conditional statements allow your program to make decisions based on conditions. The if statement checks a condition in parentheses, and if true, executes the code block below it. Use else if to check additional conditions when the previous ones were false. The else block executes when none of the previous conditions were true. Conditions typically use comparison operators like >= (greater than or equal).

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
 
int main() {
int score = 75;
if (score >= 90) {
std::cout << "Grade: A" << std::endl;
} else if (score >= 80) {
std::cout << "Grade: B" << std::endl;
} else if (score >= 70) {
std::cout << "Grade: C" << std::endl;
} else {
std::cout << "Grade: F" << std::endl;
}
return 0;
}
Breakdown
1
if (score >= 90) {
First condition: checks if score is 90 or higher
2
std::cout << "Grade: A" << std::endl;
Executed only when first condition is true
3
} else if (score >= 80) {
Alternative condition checked if first was false
4
} else if (score >= 70) {
Another alternative condition for score 70-79
5
} else {
Final fallback block when all conditions are false