capypad
0 day streak
cpp / beginner
Snippet

Making Decisions with If-Else Statements

If-else statements allow your program to make decisions based on conditions. The code checks the score variable against multiple thresholds. If the first condition is false, it moves to the next else if. If all conditions are false, the else block executes. Only one block runs depending on which condition is true.

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 = 85;
 
if (score >= 90) {
std::cout << "Excellent! Grade: A" << std::endl;
} else if (score >= 70) {
std::cout << "Good job! Grade: B" << std::endl;
} else if (score >= 50) {
std::cout << "Passed! Grade: C" << std::endl;
} else {
std::cout << "Failed. Grade: F" << std::endl;
}
 
return 0;
}
Breakdown
1
int score = 85;
Variable storing the test score
2
if (score >= 90) {
First condition: checks if score is 90 or higher
3
else if (score >= 70) {
Second condition: checks if score is 70-89
4
else if (score >= 50) {
Third condition: checks if score is 50-69
5
else {
Executes when all previous conditions are false
6
std::cout << "Failed. Grade: F" << std::endl;
Outputs failure message for scores below 50