Professional Documents
Culture Documents
In this example, the program checks the Each condition is an expression that
value of num. evaluates to either true or false.
If num is greater than 0, the message "The The if clause checks the first condition, and
number is positive" will be printed. if it is true, the corresponding code block is
If num is less than 0, the message "The executed.
number is negative" will be printed. If the first condition is false, the program
Otherwise, if both conditions are false, the moves to the next else if clause and
message "The number is zero" will be evaluates its condition.
printed. This process continues until a condition is
found to be true, in which case the
Nested If…else Statements corresponding code block is executed.
You can also nest if...else statements within other If none of the conditions are true, the code
if...else statements to create more complex block within the else clause is executed.
decision-making structures.
This allows you to test multiple conditions and Example of an If…else if…else Statement
execute different code blocks based on those
conditions.
NESTED DECISIONS
Nested Decisions
The practice of placing one or more if...else
statements inside another if or else block.
Syntax of a Switch Statement
This technique enables you to handle complex
The expression is evaluated, and its value
decision scenarios where multiple conditions
is compared to the constants specified in
need to be evaluated sequentially.
each case label.
These provide greater flexibility and granularity
If the value matches a case constant, the
when designing your program's logic.
corresponding code block is executed.
The break statement is used to exit the
switch statement after executing the
corresponding code block.
If the value doesn't match any case
constant, the code block within the default
label is executed (optional).
IF SWITCH
Example 1
You are to guess my favorite number which lies
between the values 1 – 5.
o Note: My favorite number is 3.
IF–ELSE – Evaluates my guess if it is equal to 3.
SWITCH – Evaluates my guess for each values of
1 – 5; and returns true if it is equal to 3.
Example 2
You are to check if the input field for birth gender is
Male or Female
IF–ELSE – Evaluates my input if it is Male or
Female.
SWITCH – Checks for value of gender.