Introduction
In C#, conditional statements allow you to make decisions based on specific conditions. The most common conditional statements are if
, if-else
, and else if
. Let’s break down each type with syntax, explanations, and examples.
1. if Statement
The if
statement evaluates a condition. If the condition is true, it executes a block of code; if it’s false, it skips the code block.
Syntax:
if (condition)
{
// Code to execute if condition is true
}
Example
int age = 20; if (age >= 18) { Console.WriteLine("You are eligible to vote."); }
In this example, if age
is greater than or equal to 18, it will print “You are eligible to vote.” If age
is less than 18, nothing happens, as there is no alternate path specified.
2. if-else Statment
The if-else
statement provides an alternative block of code to execute if the condition in the if
statement is false.
Syntax
if (condition)
{
// Code to execute if condition is true
}
else
{
// Code to execute if condition is false
}
Example
int age = 15; if (age >= 18) { Console.WriteLine("You are eligible to vote."); } else { Console.WriteLine("You are not eligible to vote."); }
In this example, if age
is less than 18, the program prints “You are not eligible to vote.” Here, the else
block provides a fallback for when the if
condition is false.
3. else-if Statment
he else if
statement allows you to check multiple conditions. After an if
statement, you can use one or more else if
statements to test additional conditions. If any condition evaluates to true, its corresponding code block executes, and the rest are skipped. If none of the if
or else if
conditions are true, you can add an optional else
block to provide a final fallback.
Syntax
if (condition1)
{
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition1 is false and condition2 is true
}
else if (condition3)
{
// Code to execute if condition1 and condition2 are false and condition3 is true
}
else
{
// Code to execute if all previous conditions are false
}
Example
int marks = 85; if (marks >= 90) { Console.WriteLine("Grade: A"); } else if (marks >= 80) { Console.WriteLine("Grade: B"); } else if (marks >= 70) { Console.WriteLine("Grade: C"); } else { Console.WriteLine("Grade: F"); }
In this example:
- If
marks
is 90 or higher, it will print “Grade: A”. - If
marks
is between 80 and 89, it will print “Grade: B”. - If
marks
is between 70 and 79, it will print “Grade: C”. - If none of the above conditions are met (meaning
marks
is below 70), it will print “Grade: F”.