capypad
0 day streak
cpp / beginner
Snippet

If-Else Decision Making

If-else statements allow programs to make decisions based on conditions. The code evaluates each condition in order, executing the block for the first true condition and skipping the rest. Multiple else if clauses create a chain of tests. The logical operators && (AND) and || (OR) combine multiple conditions - here age must be at least 18 AND less than 65 for the adult category.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;
 
int main() {
int score = 85;
if (score >= 90) {
cout << "Grade: A - Excellent!" << endl;
} else if (score >= 80) {
cout << "Grade: B - Good job!" << endl;
} else if (score >= 70) {
cout << "Grade: C - Satisfactory" << endl;
} else if (score >= 60) {
cout << "Grade: D - Needs improvement" << endl;
} else {
cout << "Grade: F - Failed" << endl;
}
cout << "\nAge check: " << endl;
int age = 20;
if (age >= 18 && age < 65) {
cout << "You are an adult eligible to work" << endl;
} else if (age < 18) {
cout << "You are a minor" << endl;
} else {
cout << "You are a senior citizen" << endl;
}
return 0;
}
Breakdown
1
if (score >= 90) {
First condition checking for the highest grade threshold
2
else if (score >= 80) {
Alternative condition tested only if previous condition was false
3
age >= 18 && age < 65
Compound condition using && requiring both subconditions to be true
4
else {
Final fallback block executed when no previous conditions were true