cpp / beginner
Snippet
If-Else Statements: Making Decisions in Code
If-else statements allow your program to make decisions based on conditions. The program evaluates a condition in parentheses; if it's true, the code inside the first block executes. If it's false, the program checks else if conditions in sequence. If no conditions are met, the else block runs. Conditions use comparison operators like >= (greater than or equal), == (equal), and != (not equal). The if-else chain is evaluated from top to bottom until a true condition is found.
snippet.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 << "Excellent!" << std::endl;} else if (score >= 70) {std::cout << "Good job!" << std::endl;} else if (score >= 50) {std::cout << "Pass" << std::endl;} else {std::cout << "Failed" << std::endl;}return 0;}
Breakdown
1
if (score >= 90)
First condition checked: if score is 90 or higher
2
else if (score >= 70)
Second condition only checked if first was false
3
else if (score >= 50)
Third condition only checked if previous conditions were false
4
else
Final block that executes if all conditions were false
5
{ std::cout << "Excellent!" << std::endl; }
Code block enclosed in braces executes when its condition is true