capypad
0 day streak
cpp / beginner
Snippet

If-Else Statements: Making Decisions

If statements allow your program to make decisions based on conditions. The program evaluates the condition in parentheses; if true, the first block executes. Else-if adds more conditions to check. Else catches any case where none of the above conditions were true.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
 
int main() {
int number = 10;
if (number > 0) {
std::cout << "Number is positive" << std::endl;
} else if (number < 0) {
std::cout << "Number is negative" << std::endl;
} else {
std::cout << "Number is zero" << std::endl;
}
return 0;
}
Breakdown
1
if (number > 0) {
First condition: checks if number is greater than 0
2
} else if (number < 0) {
Second condition: checks if number is less than 0 (only if first was false)
3
} else {
Final block: executes only if all above conditions were false