Conditional statements in CPP

conditional_statement_cpp


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:

if statement

Real-Life Example
: Checking if a person is eligible to vote.


if_statement
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:

else statement

Real-Life Example: Checking if a store is open.

else_statement

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:

else if

Real-Life Example: Grading a student based on their score.

else_if
This program assigns grades based on the 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:

switch statement

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.

switch_statement
In this code, the 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.

nested condition
In this example, the program first checks if the person is a senior. If not, it checks their membership status to apply the relevant discount.

Post a Comment

Your comment will be visible after approval.
© TechTestLog. All rights reserved. Premium By Raushan Design
//My script