If Statements

Lesson 14
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

In C#, if statements allow you to control the flow of your program based on certain conditions. The basic syntax for an if statement is:


if (condition)
{
    // code to execute if the condition is true
}

The condition is an expression that evaluates to either true or false. If the condition is true, the code inside the curly braces will be executed. If the condition is false, the code inside the curly braces will be skipped.

Here’s an example of an if statement:


int num = 10;

if (num > 5)
{
    Console.WriteLine("The number is greater than 5.");
}

In this example, we’re declaring an integer variable num and assigning it the value 10. We’re then using an if statement to check if num is greater than 5. Since 10 is greater than 5, the code inside the curly braces will be executed and the message “The number is greater than 5.” will be printed to the console.

We can also use an else statement to provide an alternative code block to execute if the condition in the if statement is false:


int num = 2;

if (num > 5)
{
    Console.WriteLine("The number is greater than 5.");
}
else
{
    Console.WriteLine("The number is less than or equal to 5.");
}

In this example, we’re using an if statement to check if num is greater than 5. Since 2 is less than 5, the code inside the else block will be executed and the message “The number is less than or equal to 5.” will be printed to the console.

We can also use else if statements to provide additional conditions to check:


int num = 0;

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

In this example, we’re using an if statement to check if num is greater than 0. If it is, the message “The number is positive.” will be printed to the console. If it is not, the program will move on to the else if statement, which checks if num is less than 0. If it is, the message “The number is negative.” will be printed to the console. If num is not greater than 0 or less than 0, the program will move on to the else block, which prints the message “The number is zero.” to the console.