0
0
C Sharp (C#)programming~5 mins

Else-if ladder execution in C Sharp (C#)

Choose your learning style9 modes available
Introduction

An else-if ladder helps your program choose between many options by checking conditions one after another.

When you want to check multiple conditions in order, like grading scores.
When you need to decide between several categories, such as age groups.
When you want to run different code based on user input choices.
When you want to handle different error types separately.
When you want to assign different messages based on temperature ranges.
Syntax
C Sharp (C#)
if (condition1)
{
    // code if condition1 is true
}
else if (condition2)
{
    // code if condition2 is true
}
else if (condition3)
{
    // code if condition3 is true
}
// ...
else
{
    // code if none of the above conditions are true
}

The conditions are checked from top to bottom.

Only the first true condition's code runs, then the rest are skipped.

Examples
This checks if a number is positive, negative, or zero and prints the result.
C Sharp (C#)
int number = 10;
if (number > 0)
{
    Console.WriteLine("Positive number");
}
else if (number < 0)
{
    Console.WriteLine("Negative number");
}
else
{
    Console.WriteLine("Zero");
}
This checks the grade character and prints a message accordingly.
C Sharp (C#)
char grade = 'B';
if (grade == 'A')
{
    Console.WriteLine("Excellent");
}
else if (grade == 'B')
{
    Console.WriteLine("Good");
}
else if (grade == 'C')
{
    Console.WriteLine("Average");
}
else
{
    Console.WriteLine("Needs Improvement");
}
Sample Program

This program asks for your age and tells you which age group you belong to using an else-if ladder.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Enter your age:");
        int age = int.Parse(Console.ReadLine() ?? "0");

        if (age < 13)
        {
            Console.WriteLine("You are a child.");
        }
        else if (age < 20)
        {
            Console.WriteLine("You are a teenager.");
        }
        else if (age < 60)
        {
            Console.WriteLine("You are an adult.");
        }
        else
        {
            Console.WriteLine("You are a senior.");
        }
    }
}
OutputSuccess
Important Notes

Make sure conditions do not overlap to avoid confusion.

The else block is optional but useful for handling all other cases.

Use else-if ladder when you have multiple exclusive conditions to check.

Summary

Else-if ladder checks multiple conditions one by one.

Only the first true condition runs its code.

Use else to catch all other cases not covered by conditions.