If-Else Statements in C#

If-Else Statements in C# with Examples

In this article, I am going to discuss If-Else Statements in C# with Examples. Please read our previous article, where we discussed Control Flow Statements in C# with examples. Before understanding if-else statements, let us first understand the Selection Statements in C Language.

What is Selection or Branching Control Flow Statements in C#?

It is also called Decision Making. Decision Making in a programming language is similar to decision-making in real life. In programming also, we face some situations where we want a certain block of code to be executed when some condition is fulfilled. The decision-making statements in C# allow us to make a decision, based upon the result of a condition.

Selection or Branching Statements in C# allow us to control the flow of program execution on the basis of the outcome of an expression or state of a variable known during run time. It executes different sections of code depending on a specific condition or the value of the variable. Selection statements can be divided into the following categories:

  1. if-else statements (I will discuss in this article)
  2. switch statements (I will discuss in the next article)
If Statement in C# Language:

It executes a block of statements (one or more instructions) when the condition in the if block is true and when the condition is false, it will skip the execution of the if block. Following is the syntax to use the if block in the C# language.

If Statement in C# Language

Flow Chart of If Block:

Let us understand how we will represent the execution flow of the if block using a flow chart. The starting point is represented by the oval symbol. And the flow will be from the condition and the condition is represented by a diamond shape. Here, first, we need to check the condition. And for every condition, two options are there i.e. if conditions are successful (condition is true) and if conditions are failed (condition is false). That means two situations are there i.e. TRUE and FALSE.

Suppose, the condition is TRUE, then all statements are defined inside the if block will get executed. And the statements we are representing in the flow chart with the help of a parallelogram symbol. And after the execution of the statements, the control will come to end. Suppose, the condition is false, then without executing any statement inside the if block, the control will come to the end. For better understanding, please have a look at the below diagram which represents the flow chart of the if conditional statement.

Flow Chart of If Block

Note: Here, the block of statements executes only when the condition is true. And if the condition is false, then it will skip the execution of the statements.

For example to check whether the number is greater than 10 using the if statement in C# Language

Here, we will take the number from the user and then we will check whether that number is greater than 10 or not using the if Statement in C# Language.

The following program exactly does the same. In the below program, inside the main method, we are declaring one integer variable i.e. number, and then we are taking the input from the user and storing it in the number variable.

After reading the input we are checking whether the given number is greater than 10 or not. If the number > 10, then if the condition is true and, in that case, the two statements that are present inside the if block is executed else if the condition is false, then the if block statements will be skipped.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int number;
            Console.WriteLine("Enter a Number: ");
            number = Convert.ToInt32(Console.ReadLine());
            if (number > 10)
            {
                Console.WriteLine($"{number} is greater than 10 ");
                Console.WriteLine("End of if block");
            }
            Console.WriteLine("End of Main Method");
            Console.ReadKey();
        }
    }
}
Output:

If we take 15 as an input, 15 > 10 means the condition is true, then if block statement gets executed.

example to check whether the number is greater than 10 using the if statement in C# Language

If we take 5 as an input, 5 > 10 means the condition is false, then the if block statements will be skipped

Check whether the number is greater than 10 using the if statement in C# Language

If Statement without Curly Braces in C# Language

In the declaration of if block if we do not specify statements using blocks {} (curly braces), then only the first statement will be considered as the if block statement. To understand this, please have a look at the below example.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int number;
            Console.WriteLine("Enter a Number: ");
            number = Convert.ToInt32(Console.ReadLine());
            if (number > 10)
                Console.WriteLine($"{number} is greater than 10 ");
            Console.WriteLine("End of Main Method");
            Console.ReadKey();
        }
    }
}

As you can see, in the above example, we have not specified the curly braces to define the if block. In this case, only the first statement will be considered as the if block statement. The second statement will not be a part of the if block. For a better understanding, please have a look at the below image. The statement which is in red color will belong to the if block and the statement which is in the black color do not belong to the if block.

If Statement without Curly Braces in C# Language

So, when you execute the above program, irrespective of the condition, the black statement is always going to be executed as it is not part of the if block. The red statement is only executed when the if condition is true. For a better understanding, please have a look at the below image.

If Statement without Curly Braces in C# Language

If Else Statements in C# Language:

The If-Else block in C# Language is used to provide some optional information whenever the given condition is FALSE in the if block. That means if the condition is true, then the if block statements will be executed, and if the condition is false, then the else block statement will execute. Following is the syntax to use the IF ELSE block in the C# language.

If Else Statements in C# Language

Note: The point that you need to remember is that only one block of statement i.e. either if block or else block is going to be executed at a time. So, if the condition is TRUE if block statements get executed and if the condition is FALSE, then else block statements get executed.

Is it mandatory to use else block?

No, it is not mandatory to use else block. It is an optional block. You can use only if block also. If you want to provide some information when the condition is failed, then you need to use this optional else block.

Flow Chart of If-Else Block:

The flow chart of the if-else block is almost similar to the if block. In this case, when the condition is true, the if block statements get executed and when the condition is false, the else block statements get executed. For better understanding, please have a look at the below image which shows the flow chart of the if-else block.

Flow Chart of If-Else Block

Note: In C# Programming Language, if and else are reserved words. The expressions or conditions specified in the if block can be a Relational or Boolean expression or condition that evaluates to TRUE(1) or FALSE(0). Now let us see some examples to understand the if-else conditional statements.

Example to Check Whether a Number is Even or Odd using If Else Statements in C# Language

Here we will take the input number from the user and then we will check whether that number is even or odd using the if-else statement in C# Language. The following program exactly does the same.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int number;
            Console.WriteLine("Enter a Number: ");
            number = Convert.ToInt32(Console.ReadLine());
            if (number % 2 == 0)
            {
                Console.WriteLine($"{number} is an Even Number");
            }
            else
            {
                Console.WriteLine($"{number} is an Odd Number");
            }

            Console.ReadKey();
        }
    }
}

In the above program, inside the main method, we are declaring one integer variable i.e. number and then we are reading input from the user and storing the value in the number variable. After reading the input we are checking whether the given number is even or odd. An Even number is a number that is divisible by 2. If number % 2 equals 0, then the if condition is true and, in that case, we are printing a message that it is an even number and if the condition is false then we are printing a message that it is an odd number.

For example,

If we take 16 as an input, 16%2 == 0 means the condition is true, then the if block statement gets executed. And the output will be 16 is an Even Number.

Example to Check Whether a Number is Even or Odd using If Else Statements in C# Language

If we take 13 as an input, 13%2 == 0 means the condition is false, then the else block statements get executed. And the output will be 13 is an Odd Number.

Example to Check Whether a Number is Even or Odd using If Else Statements in C# Language

If and Else Block without Curly Braces in C# Programming Language

In the declaration of if block or else block if we do not specify statements using curly braces {}, then only the first statement will be considered as the if block or else block statement. Let us understand this with an example. Please have a look at the below code.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 10;
            if (number == 10)
                Console.WriteLine("Hi");
            else
                Console.WriteLine("Hello");
            Console.WriteLine("Bye");
            
            Console.ReadKey();
        }
    }
}

As you can see, in the above example, while creating the if and else block we have not specified the curly braces. So, in this case, the first Console.WriteLine statement will belong to the if block. After the else statement, we have two Console.WriteLine statements. Here, the Console.WriteLine statement which printing the Hello message will belongs to the else block only. The next Console.WriteLine statement which printing the message bye will not belong to else block. Now, if you execute the above program then you will get the following output.

If and Else Block without Curly Braces in C# Programming Language

Now, if we replace the Hello statement inside the if block, then we will get an ERROR. The reason is that not more than one statement gets executed without braces. One statement will execute inside the if block. If we want to execute more than one statement then you should use braces and all the statements will be inside the braces. For better understanding, please have a look at the below example.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 10;
            if (number == 10)
                Console.WriteLine("Hi");
                Console.WriteLine("Hello");
            else  
               Console.WriteLine("Bye");
            
            Console.ReadKey();
        }
    }
}

The following code works fine. Here, we are using curly braces in the if block.

using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 10;
            if (number == 10)
            {
                Console.WriteLine("Hi");
                Console.WriteLine("Hello");
            }
            else  
               Console.WriteLine("Bye");
            
            Console.ReadKey();
        }
    }
}

Note: For every, if condition statement else block is optional. But for every else block if block is compulsory. The purpose of the ‘if’ statement in a program is to allow multiple execution paths for varying user inputs, making it more interactive!

Nested If-Else Statements in C# Language:

When an if-else statement is present inside the body of another “if” or “else” then this is called nested if-else. Nested ‘if’ statements are used when we want to check for a condition only when the previous dependent condition is true or false. C# allows us to nested if statements within if statements, i.e. we can place an if statement inside another if statement.

What is the Nested If block?

Nested if block means defining if block inside another if block. We can also define the if block inside the else blocks. Depending on our logic requirements, we can use nested if block in n number of ways. You can define nested if block at many levels.

Nested If-Else Statement Syntax in C# Language:

Please have a look at the below image which shows the different ways to use the nested if block in C# Language.

Nested If-Else Statement Syntax in C# Language

Now, we will take one example and try to understand the flow chart. We are taking the following syntax. Here, we have an if-else block inside the if block, as well as, an if-else block inside the else block.

Nested If-Else Statements in C# Language

How Nested IF ELSE work in C# Language?

First, it will check the first if condition i.e. the outer if condition and if it is true, then the outer else block will be terminated. So, the control moves inside the first or the outer if block. Then again it checks the inner if condition and if the inner if condition is true, then the inner else block gets terminated. So, in this case, the outer if and inner if block statements get executed.

Now, if the outer if condition is true, but the inner if condition is false, then the inner if block gets terminated. So, in this case, the outer if and inner else block statements get executed.

Now, if the outer if condition is false, then the outer if block gets terminated and control moves to the outer else block. And inside the outer else block, again it checks the inner if condition, and if the inner if condition is true, then the inner else block gets terminated. So, in this case, the outer else and inner if block statements get executed.

Now, if the outer if condition is false as well as the if condition inside the outer else blocks also failed, then the if block gets terminated. And in this case, the outer else and inner else block statements get executed. This is how statements get executed in Nested if. Now we will see the flow chart of nested if blocks.

Flow chart of Nested If Block in C# Language:

First, have a look at the below diagram which shows the flow chart of the nested if-else statement.

Flow chart of Nested If Block in C# Language

First, it will check the outer if condition, and if the outer if condition is true, then the control comes inside and it will check the inner if condition, and if the inner if condition is true, then the outer if block statements and inner if block statements get executed. And after execution, it will come to end.

Suppose, the outer if condition is true but the inner if condition is failed, then the outer if block statements and the inner else block statement get executed. And once the statement gets executed, it will come to end.

Suppose, the outer if condition is failed, then the control directly comes to the else block and checks the inner if condition. And again, for the inner if condition two options are there. If the inner if condition is true, then it will execute the outer else block and inner if block statement, and if the inner if condition is false, then it will execute the outer else block and inner else block statements and then comes to end.

Example to understand Nested IF-ELSE Statements in C# Language:
using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 10;
            if (i == 10)
            {
                if (i < 15) 
                    Console.WriteLine("i is smaller than 15"); 
                if (i < 12)
                    Console.WriteLine("i is smaller than 12 too");
                else
                    Console.WriteLine("i is greater than 15");
            }
 
            Console.ReadKey();
        }
    }
}
Output:

Example to understand Nested IF-ELSE statements in C# Language

Ladder if-else statements in C# Language:

In Ladder if-else statements one of the statements will be executed depending upon the truth or false of the conditions. If condition1 is true then Statement 1 will be executed and so on but if all conditions are false then Statement 3 will be executed. The C# if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C# else-if ladder is bypassed. If none of the conditions are true, then the final else statement will be executed.

Ladder if-else statements in C# Language

Syntax to use Ladder if-else statements in C# Language:

Syntax to use Ladder if-else statements in C# Language

Example to understand Ladder If-Else Statements in C# Language:
using System;
namespace ControlFlowDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 20;
            if (i == 10)
            {
                Console.WriteLine("i is 10");
            }
            else if (i == 15)
            {
                Console.WriteLine("i is 15");
            }
            else if (i == 20)
            {
                Console.WriteLine("i is 20");
            }
            else
            {
                Console.WriteLine("i is not present");
            }

            Console.ReadKey();
        }
    }
}

Output: i is 20

In the next article, I am going to discuss Switch Statements in C# Language with Examples. Here, in this article, I try to explain If-Else Statements in C# Language with Syntax, Flowchart, and Examples. I hope you enjoy this If-Else Statements in C# Language with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.