C++ If Statement

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.

Tutorials dojo strip



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 the if 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:

OperatorMeaning
<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

C++

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.

C++




Using Variables in an if Statement

Instead of comparing fixed numbers, you can use variables.

Example

C++

Explanation:

  • horsepower1 is 500.
  • horsepower2 is 450.
  • Since 500 is greater than 450, the program prints:
    “The first car has more horsepower.”

Tutorials dojo strip