C# Conditional Statements

Level : Beginner
Mentor: Shailendra Chauhan
Duration : 00:02:30

if statement:

An if statement is used to conditionally execute a block of code based on a specified condition.

Example:

int age = 18;
if (age >= 18)
{
    Console.WriteLine("You are an adult.");
}

if-else statement:

An if-else statement is used to execute one block of code if a condition is true and another block if the condition is false.

Example:

int num = 7;
if (num % 2 == 0)
{
    Console.WriteLine("Even");
}
else
{
    Console.WriteLine("Odd");
}

nested if statement:

A nested if statement is an if statement inside another if statement, allowing for more complex conditional logic.

Example:

int num = 12;
if (num > 0)
{
    if (num % 2 == 0)
    {
        Console.WriteLine("Positive and even");
    }
    else
    {
        Console.WriteLine("Positive and odd");
    }
}

if-else-if ladder:

An if-else-if ladder is used when you have multiple conditions to check, and each condition is evaluated sequentially.

Example:

int score = 85;
if (score >= 90)
{
    Console.WriteLine("A");
}
else if (score >= 80)
{
    Console.WriteLine("B");
}
else if (score >= 70)
{
    Console.WriteLine("C");
}
else
{
    Console.WriteLine("D");
}

switch statement:

Some programming languages have a switch statement for selecting among multiple code blocks based on the value of an expression.

Example:

int option = 2;
string result;
switch (option)
{
    case 1:
        result = "One";
        break;
    case 2:
        result = "Two";
        break;
    case 3:
        result = "Three";
        break;
    default:
        result = "Invalid option";
        break;
}
Console.WriteLine(result);
Self-paced Membership
  • 24+ Video Courses
  • 825+ Hands-On Labs
  • 400+ Quick Notes
  • 125+ Skill Tests
  • 10+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this