The if statement is one of the most important decision-making tools in C++. It allows a program to perform certain actions only when a specific condition is true.
Purpose: To check a condition and execute a block of code if the condition evaluates to true.
Usage: Commonly used in conditional operations, comparisons, and decision-making tasks.
Syntax of if Statement
The basic syntax of an if statement is:
Explanation:
condition: This is a Boolean expression that evaluates totrueorfalse.Curly braces
{}are used to define the block of code that runs when the condition is true.If the condition is false, the code inside the block is skipped.
Example 1: Simple if Statement
Output:
The condition
number > 0is true, so the message is printed.If
numberwere-5, nothing would be printed because the condition would be false.
Example 2: if Statement with User Input
Explanation:
The program checks the user’s input.
Only if
age >= 18is true, the message is displayed.This is an example of real-life decision-making in programming.
Example 3: Using Relational Operators in if Statement
Here, the relational operator
>=is used to check if marks are 50 or above.
Output (if marks = 60):
Output (if marks = 40):
Nothing is printed because the condition is false.
Tips for Using if Statements
Always use relational or logical expressions in the condition.
Curly braces
{}are optional if there is only one statement, but it is recommended for clarity.
This works, but using
{}is safer:
Combine multiple conditions using logical operators: