In real-time, we can come across scenarios where we have to make one decision by checking multiple conditions. Using C# Nested if statements, we can write several if or else if conditions inside one if or else if condition.
The syntax of the C# Nested If Statement is
If <condition> { If <condition> { Statements; } else if<condition> { Statements; } else Default statements } else Default statements;
C# Nested If Statement Example
For example, let us assume that for a particular job requirement. The job profile is as follows:
- The candidate should be from it or the CSC department.
- Academic percentage >= 60
- Age < 50
If all the above conditions are satisfied, then the person is eligible for the post. Let us write the C# code for the above scenario.
using System; namespace CSharp_Tutorial { class Program { static void Main() { Console.WriteLine("Enter your Department"); string Department = (Console.ReadLine()); if (Department.ToUpper() == "IT" || Department.ToUpper() == "CSC") { Console.WriteLine("Enter your Percentage"); int Percentage = int.Parse(Console.ReadLine()); if (Percentage >= 60) { Console.WriteLine("Enter your age"); int Age = int.Parse(Console.ReadLine()); if (Age < 50) { Console.WriteLine("You are eligible for this post"); } else Console.WriteLine("Your age is not suitable for the requirement"); } else Console.WriteLine("Your Percentage is not suitable for the requirement"); } else Console.WriteLine("Your qualification is not suitable for the requirement"); } } }
In this C# Nested If Statement example, we have given Department name as ‘CSC’. Since it satisfies the condition, it enters into the inner if
Next, it asks for the Percentage.
The Percentage is given as 40.
Since this percentage condition failed, the Percentage should be >= 60 to enter into the inner if, i.e., age condition.
The compiler exits from the loop and prints the else part, i.e.,
Your Percentage is not suitable for the requirement.
Let me try the Percentage as 60, and the age as 28, and you get a different result.
Here, we have given a good Percentage, but the inner if statement condition age < 50 fails. So, the inner else block statement is printed.
Enter your Department
IT
Enter your Percentage
75
Enter your age
54
Your age is not suitable for the requirement
This time, we have given the wrong department, so it resulted in the main else block statement.
Enter your Department
ece
Your qualification is not suitable for the requirement