Conditional statements in C++ allow your program to make decisions based on certain conditions. The main types of conditional statements in C++ are if
, else
, and switch
. These control structures allow you to execute specific blocks of code depending on whether certain conditions are met.
Here’s a breakdown of each conditional statement along with real-life examples in code.
The if
Statement
The if
statement evaluates a condition, and if it’s true
, the code within the if
block is executed. If it’s false
, the code within the block is skipped.
Syntax:
Here, the program checks if
age
is 18 or older. If the condition is true
, it displays the eligibility message.The else
Statement
The else
statement works with if
and provides an alternative block of code to execute if the if
condition is false
.
Syntax:
In this example, if the current hour
is less than 18 (6 PM), it prints that the store is open; otherwise, it indicates the store is closed.
The else if
Statement
When there are multiple conditions, else if
allows you to check additional conditions in sequence after the first if
condition.
Syntax:
score
value. It checks each condition sequentially and outputs the corresponding grade.The switch
Statement
The switch
statement is useful for checking a variable against multiple possible constant values. Each possible value is a case
within the switch
.
Syntax:
The break
statement exits the switch
after a case
is executed, so it doesn't proceed to the next case
.
Real-Life Example: Determining the day of the week.
day
variable is checked against each case
. If day
is 3
, it prints "Wednesday."Nested Conditionals
You can also nest if
, else if
, and else
statements to check more complex conditions.
Real-Life Example: Determining travel discounts based on age and membership status.