If statement is used to make decisions in your code based on certain conditions.
Syntax
if (condition)
{
// code block to execute if condition is true
}
else
{
// code block to execute if condition is false
}
Example
int age = 10;
if (age > 18)
{
Console.WriteLine("Welcome to the club");
}
else if (age == 18)
{
Console.WriteLine("You are not welcome today");
}
else
{
Console.WriteLine("You are not welcome..!");
}
The result will be "You are not welcome..!"
In this code
int age = 10; // initializes an integer variable age with a value of 10.
The if statement checks the value of age. If the age is greater than 18, it prints "Welcome to the club".
If the age is not greater than 18, the else if statement checks if the age is equal to 18. If it is, it prints "You are not welcome today".
If neither of the above conditions is true, the else statement is executed, which prints "You are not welcome..!".
Given that the age is 10, the output of this code would be: "You are not welcome..!" since the age is not greater than 18 and it's also not equal to 18.