Nested If In C#
Nested If In C#
Prepared by
Abdulstar Badia Ramadan
Teacher
Mr.Ayad
1
2024/12/15
Nested If-------------------------------------1
What is a Nested Statment---------------2
How Does It Work--------------------------3 Give
an Example---------------------------4
**************************************
2
Nested If
3
decision-making by evaluating conditions at multiple
levels. Here’s an example:
2.
4
************************************************
Explanation:
• The outer if checks if x is greater than 5.
• Inside that block, there’s a second if (nested) which
checks if y is greater than 15.
• If both conditions are true, the first message is printed. If
only the outer condition is true but not the inner one, the
second message is printed.
5
• If the outer condition is false, the else block prints a
different message.
6
A nested if statement in C# works by allowing you to place
one if statement inside another. This structure creates a
hierarchy of conditions that can be evaluated in sequence.
Each if statement checks a condition, and if that condition
evaluates to true, the corresponding block of code
executes. If it evaluates to false, the program can move on
to check other conditions or execute alternative code.
7
3. Else Statements: You can also use else or else if with
both the outer and inner if statements to handle
alternative scenarios.
Example Breakdown:
************************************************
How It Works:
8
1. The program first evaluates the outer if (checking if
number is greater than 0).
- If true, it prints "The number is positive."
- Then, it evaluates the inner if (checking if number is
even).
- If the inner if is true, it prints "The number is even."
- If false, it prints "The number is odd."
9
************************************************
Benefits of Nested If Statements:
- Complex Logic: They allow for more complex
decisionmaking processes.
- Organized Code: They can help keep related conditions
bundled together for better readability.
************************************************
Considerations:
- Readability: Too many nested if statements can make
code difficult to read and maintain. In such cases, consider
using other structures like switch statements or logical
operators to simplify the logic.
************************************************
10