In C#, an if statement is used to make decisions in your code. It checks if a certain condition is true, and if it is, it runs a block of code. If the condition is false, it skips that block.
Basic Structure of an if Statement
Here’s a simple example of an if statement in C#:
int number = 10;
if (number > 5)
{
Console.WriteLine("The number is greater than 5.");
}
In this example:
number > 5is the condition. It checks ifnumberis greater than 5.- If the condition is true (which it is, since 10 is greater than 5), the code inside the curly braces
{}will run. - So, the message "The number is greater than 5." will be printed.
Adding an Else Statement
Sometimes, you want to do one thing if a condition is true and something else if it's false. You can use an else statement for this:
int number = 3;
if (number > 5)
{
Console.WriteLine("The number is greater than 5.");
}
else
{
Console.WriteLine("The number is 5 or less.");
}
Here:
- Since
numberis not greater than 5, the condition is false. - The code inside the
elseblock will run, printing "The number is 5 or less."
Adding Multiple Conditions with Else If
If you have more than two choices, you can use else if to add extra conditions:
int number = 5;
if (number > 5)
{
Console.WriteLine("The number is greater than 5.");
}
else if (number == 5)
{
Console.WriteLine("The number is exactly 5.");
}
else
{
Console.WriteLine("The number is less than 5.");
}
In this example:
- The program checks each condition in order.
- Since
number == 5, the message "The number is exactly 5." will be printed.

Perfect keep going,Bilal
ReplyDeleteAmazing, man!!!
ReplyDeleteWow
ReplyDeleteKeep going
ReplyDeleteThe greatest
ReplyDelete