Decisions in C#

In C#, decisions or conditional statements are used to execute different blocks of code based on certain conditions. These conditions evaluate to either true or false, and depending on the result, specific code blocks are executed. Here are the primary conditional statements in C#:

if Statement: The if statement is the most basic conditional statement. It executes a block of code if a specified condition is true.

int x = 10;
if (x > 5)
{
    // This block will execute if x is greater than 5
    Console.WriteLine("x is greater than 5");
}

if-else Statement: The if-else statement allows us to execute one block of code if the condition is true and another block if it’s false.

int x = 3;
if (x > 5)
{
    // This block will execute if x is greater than 5
    Console.WriteLine("x is greater than 5");
}
else
{
    // This block will execute if x is not greater than 5
    Console.WriteLine("x is not greater than 5");
}

else-if Statement: We can use the else-if statement to check multiple conditions one by one and execute the block of code associated with the first true condition.

int x = 3;
if (x > 5)
{
    Console.WriteLine("x is greater than 5");
}
else if (x < 5)
{
    Console.WriteLine("x is less than 5");
}
else
{
    Console.WriteLine("x is equal to 5");
}

switch Statement: The switch statement is useful when we have multiple conditions to check against a single variable.

int day = 3;
switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    case 3:
        Console.WriteLine("Wednesday");
        break;
    default:
        Console.WriteLine("Other day");
        break;
}

In summary, conditional statements allow us to control the flow of our program based on different conditions, making our code more dynamic and flexible.

Leave a Comment

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