C++ provides several conditional statements that allow programs to make decisions based on logical evaluations. These conditions guide the execution of different blocks of code.
Using Conditions for Decision-Making
Programs often need to react to different situations. C++ supports logical conditions such as:
if
→ Runs a block only if the specified condition is true.else
→ Runs a block if theif
condition is false.else if
→ Introduces additional conditions when the first condition fails.switch
→ Evaluates a variable and selects a matching case.
For this lesson, we’ll focus only on the if
statement.
Comparison Operators for Conditions
These operators help check relationships between values:
Operator | Meaning |
---|---|
< | Less than |
<= | Less than or equal to |
> | Greater than |
>= | Greater than or equal to |
== | Equal to |
!= | Not equal to |
These operators define logical conditions used in if
statements.
Using if to Execute Code Conditionally
An if
statement ensures that a specific block of code runs only if a condition evaluates to true.
Syntax
if (condition) {
// Code executes only if condition is true
}
Important: C++ is case-sensitive! Writing If
or IF
instead of if
will cause an error.
Example: Simple if
Statement
The program below checks if 250 is greater than 200. Since the condition is true, the message will be displayed.
using namespace std;
int main() {
if (250 > 200) {
cout << "250cc engines have more power than 200cc ones.";
}
return 0;
}
Using Variables in an if
Statement
Instead of comparing fixed numbers, you can use variables.
Example
using namespace std;
int main() {
int horsepower1 = 500;
int horsepower2 = 450;
if (horsepower1 > horsepower2) {
cout << "The first car has more horsepower.";
}
return 0;
}
Explanation:
horsepower1
is 500.horsepower2
is 450.- Since 500 is greater than 450, the program prints:
“The first car has more horsepower.”