Virtual Classes Logo          Virtual Classes
    Read Anytime,Anywhere


Conditional Statements

Conditional Statements are used to control the flow of your program. It allows to make decisions on what code to execute in one scenario and what code to execute in another scenario.
There are two types of conditional statement provided by C++.
1-If statement
2-Switch Case statement.

1-If statement: It allows to control and execute lines of code based on whether a given condition is true or false.
e.g. use if statement to check a student result,is student cleared the exam or not?.
A true statement is one that evaluates to a nonzero number.A false statement evaluates to zero.
When you perform comparison with the relational operators, the operator will return 1 if the comparison is true, or 0 if the comparison is false.
There are a number of operators that allow these checks.
conditional statement operators
Syntex-
if condition-

if example
if-else condition-
if else example
if-else if condition-
nested if example
Ex-
If else program


2-Switch Case statements in C++ are a substitute of multiple if else statements.
Switch Case Statement compares a variable to several "integral" values ("integral" values are values that can be expressed as an integer or as a char).
Switch Case statement is not a replacement of if condition.Use Switch Case statement if you need to check a condition multipletime. If developer using multiple if condition, it decrease program performace. If coditions are less it's better to use If statement.

Syntex:

Switch Case syntex

break keyword simply stops execution of code and C++ compiler don't check/execute other case conditions. If we do not write it then C++ compiler continue checking/executing the code of other cases. If we have user default case then it will always be executed.This can lead to wrong out put of the program.

The default case is optional keyword to use in switch statement. It's good to use this to hadle any unexpected cases. Code written in default case will always be executed if there is not any matching case specified in above cases.

Ex-
Switch Case example