if-else C Sharp Language

if-else C# Language

If-else statements are fundamental constructs in programming, allowing you to make decisions and control the flow of your code based on conditions. In

g/wiki/C_Sharp_(programming_language)">C#, if-else statements provide a simple and effective way to implement branching logic. In this post, we’ll explore the basics of if-else statements in C# and provide some examples to illustrate their usage.

The Anatomy of an If-Else Statement

An if-else statement consists of the following components:

  • if keyword: It’s used to start the conditional statement.
  • Condition: A boolean expression that is evaluated to determine whether the code inside the if block should be executed.
  • else keyword (optional): If the condition is false, you can provide an alternative code block to execute using the else statement.

Example 1: Basic If-Else Statement

Let’s start with a simple example. Suppose you want to check whether a number is even or odd and display a message accordingly:

int number = 6;

if (number % 2 == 0)
{
    Console.WriteLine("The number is even.");
}
else
{
    Console.WriteLine("The number is odd.");
}

In this code, number % 2 == 0 is the condition. If the condition is true (in this case, if the number is even), the code inside the if block will execute. If it’s false (the number is odd), the code inside the else block will execute.

Example 2: If-Else If-Else Ladder

You can also create a chain of conditions using if, else if, and else to handle multiple cases. Let’s say you want to classify a student’s performance based on their exam score:

int score = 85;

if (score >= 90)
{
    Console.WriteLine("Excellent");
}
else if (score >= 70)
{
    Console.WriteLine("Good");
}
else if (score >= 50)
{
    Console.WriteLine("Pass");
}
else
{
    Console.WriteLine("Fail");
}

In this example, the program checks multiple conditions one by one, and once a true condition is found, the corresponding code block is executed.

Example 3: Nested If-Else Statements

You can also nest if-else statements to handle more complex scenarios. Here’s an example of nested if-else statements to determine whether a number is positive, negative, or zero:

int value = -5;

if (value > 0)
{
    Console.WriteLine("The number is positive.");
}
else if (value < 0)
{
    Console.WriteLine("The number is negative.");
}
else
{
    Console.WriteLine("The number is zero.");
}

Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading