Learn about conditional statements in C++, including if, if-else, if-else-if ladder, nested if, switch, and ternary operator.
if
Statementif
statement executes a block of code only if a specified condition is true
.
temperature
is greater than 30, the message is displayed.temperature > 30
), wear sunglasses.if-else
Statementif-else
statement executes one block of code if the condition is true
, and another block if it is false
.
if-else-if
Laddermarks
is 90 or more, print A+
.marks
is 80-89, print A
.marks
is 70-79, print B
.C
.if
checks if it’s red → outputs “Stop!”.else if
checks if it’s yellow → outputs “Slow down!”.else if
checks if it’s green → outputs “Go!”.else
handles incorrect inputs.if
Statementsif
inside another. Used when conditions depend on previous ones.
switch
Statementswitch
is used when multiple values need to be compared to a single variable.
switch
evaluates choice
and executes the corresponding case
block.break
prevents the execution of the next case.default
handles invalid inputs.switch
?if-else
makes the code lengthy.? :
) is a shorthand for if-else
.
cout << (age >= 18 ? "Adult" : "Minor");
Scenario | Use |
---|---|
Checking a single condition | if |
Two possibilities (true/false) | if-else |
Multiple conditions | if-else-if |
Nested conditions | nested if |
Checking one value against many cases | switch |
Simple if-else in one line | ternary operator |
if
statements for basic conditions.if-else
for two outcomes.if-else-if
for multiple choices.nested if
for dependent conditions.switch
for multiple exact matches.