Certainly! In C#, if
and else
are control flow statements used for decision-making. They allow you to execute certain blocks of code based on conditions. Here's a simple explanation with an example:
if
statement: It evaluates a condition and executes a block of code if the condition is true.
else
statement: It follows an if
statement and executes a block of code if the condition in the if
statement is false.
Here's an example:
Example
using System;
class Program
{
static void Main()
{
int number = 10;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else
{
Console.WriteLine("The number is not positive.");
}
}
}
Explanation:
number
initialized with the value 10
.if
statement checks whether number
is greater than 0
. If it is, it executes the block of code inside the curly braces {}
.if
statement is false, the else
block is executed.number
is greater than 0
, the output will be: "The number is positive."You can also have multiple conditions using else if
, which allows you to check additional conditions if the previous ones are false:
using System;
class Program
{
static void Main()
{
int number = 0;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else if (number < 0)
{
Console.WriteLine("The number is negative.");
}
else
{
Console.WriteLine("The number is zero.");
}
}
}
In this example:
number
is greater than 0
, it prints "The number is positive."number
is less than 0
, it prints "The number is negative."number
is 0
), it prints "The number is zero."