if else if else Statement in C#



if-else if-else statement – this statement is used when we want to execute a code if one of multiple condition is true.

if-else if-else statement syntax in C# :

if (condition)
{
// if this condition is true then code to be executed
}
else if (condition)
{
// if this condition is true then code to be executed
}
else if (Condition)
{
// if this condition is true then code to be executed
}
else
{
// all conditions are false then this code to be executed
}

Example of if-else if-else condition

In below example we calculate the grade for student, each student has only one grade from various grades like “first class”, “second class”, “pass class” etc.

Here we have various condition but output must be a single, so we need to use if-else if-else condition for this c# example.

int maths=60;
int biology=65;
int physics=73;

int result = (maths + biology + physics)/3;

if(result <35)
{
Response.Write("Fail");
}
else if(result>=35 && result<=50)
{
Response.Write("Pass class");
}
else if(result>50 && result<=60)
{
Response.Write("Second class");
}
else if(result>60 && result<=70)
{
Response.Write("First class");
}
else     //or else if(result>70)
{
Response.Write("Distinction class");
}

The output is:
First class

In above C# example the result value is 66, the fourth condition will be true and out put is “First class”.


Let’s take a second example to more understand about else – else if – else statement in c#.

int a = 7;
int b = 10;

if (a == b)
{
Response.Write("a and b both are equal");
}
else if (a > b)
{
Response.Write("a is greater than b");
}
else   // or else if (a < b)
{
Response.Write("b is greater than a");
}

The output is:
b is greater than a

Related ASP.Net Topics :

If Conditional Statement in C#.Net
Switch Statement in C#.Net


Subscribe us

If you liked this c#.net post, then please subscribe to our YouTube Channel for more c#.net video tutorials.

We hope that this asp.net c# tutorial helped you to understand If-Else If-Else Statement.


Next asp.net tutorial we will learn about Nested If Statement.


Leave a Reply

Your email address will not be published. Required fields are marked *