• Home
  • Conditional Statement

Conditional Statement

Agenda

Conditional Statement in C#

Testing a condition is always important in any programming language. User will often face situations where they need to test conditions (whether it is true or false) to control the flow of program. These conditions may be affected by user’s input, time factor, current environment where the program is running, etc. A statement that can be executed based on a condition is known as a “Conditional Statement”.

Five types of Conditional statements in C#

if statement is used only to specify a block of C# code to be executed if a condition is met (true).

if(condition){

Statement(s);

}

An if statement can be followed by an optional else statement, else statement is used to specify a block of
code to be executed if the condition is not met (false).

if(condition) {

Statement(s);

}

else {

Statement(s);

}

Nested if else statement in C#

Any if else statement can exist within another if else statement. Such statements are called nested if else statement.

Example:

if (outer condition)

{

if (inner condition)

{

// code to be executed

}

else

{

// code to be executed

}

}

else

{

// code to be executed

}

if else if ladder or else if statement in C#

else if statement is used to specify a new condition when first condition is false.

Example:

if(condition_1) {

//execute this statement in case condition_1 is true

Statement(s);

}

else if(condition_2) {

//execute this statement in case condition_1 is not met but condition_2 is true

Statement(s);

}

else if(condition_3) {

//execute this statement in case condition_1 and condition_2 are not met but condition_3 is true

Statement(s);

}

…..

else {

//execute this statement in case none of the above conditions are true

Statement(s);

}


int age = 10; 


if (age > 18)
{
Console.WriteLine("The person is eligible to cast the Loksabha Vote");
}
else
{
Console.WriteLine("The person is not aged enough to caste any Vote");
}

int age = 10;


if (age > 18)
{
if (age > 25)
{
Console.WriteLine("The person is eligible to cast the Loksabha Vote and contest for the election");
}
else
{
Console.WriteLine("The person is eligible to cast the Loksabha Vote but can not contest for the election");


}
else
{
Console.WriteLine("The person is not aged enough to caste any Vote");
}


Console.WriteLine("The person is not aged enough to caste any Vote");
}


int marks = 22;


if (marks >= 30 && marks < 45) { Console.WriteLine("Average - Grade D"); } else if (marks >= 45 && marks < 60) { Console.WriteLine("Good - Grade C"); } else if (marks >= 60 && marks < 80) { Console.WriteLine("Very Good - Grade B"); } else if (marks >= 80 && marks <= 100)
{
Console.WriteLine("Excellent - Grade A");
}
else
{
Console.WriteLine("Fail - No Grade");
}