<aside> If statements are fundamental building blocks for decision-making in C# programming. They allow your code to execute different paths based on conditions.
</aside>
The basic if statement evaluates a condition and executes code if the condition is true.
if (condition)
{
// Code executed when condition is true
}
int diceRoll = 6;
if (diceRoll == 1)
{
Console.WriteLine("You rolled a 1!");
}
If-Else statements provide alternative code paths based on conditions.
int price = 100;
if (price > 50)
{
Console.WriteLine("That's expensive!");
}
else
{
Console.WriteLine("That's reasonable!");
}
For multiple conditions, you can chain if-else statements:
int score = 85;
if (score >= 90)
{
Console.WriteLine("A Grade");
}
else if (score >= 80)
{
Console.WriteLine("B Grade");
}
else
{
Console.WriteLine("Try harder next time");
}
<aside> You can combine multiple conditions using logical operators:
</aside>
int age = 25;
bool hasLicense = true;
// Using AND (&&)
if (age >= 18 && hasLicense)
{
Console.WriteLine("Can drive");
}
// Using OR (||)
if (age < 13 || age > 65)
{
Console.WriteLine("Special price applies");
}