C# Conditional Statements

In Previous article we learned about C# Classes and Objects and now in this article we will learn about C# Conditional Statements using various examples.

C# Conditional Statements

C# Conditional Statement

In C#, conditional statements are used to execute specific blocks of code based on certain conditions.

Decision-making statements require a few conditions that can be evaluated by the program and set of statements that can be executed if the condition evaluates as true or another statement that can be executed when the condition values as false.

In this tutorial, we will be explaining how a conditional operator works with proper syntax explanation and some interesting examples. We will also be looking into nested and other different conditional statements.

Lets have look on flow chart of Conditional statement ,


Here, are the three types of conditional statements in C#:

1.if statement: The if statement is used to execute a block of code only if a certain condition is true. Here is the syntax:

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

here is the example of If statement,

using System;

namespace Conditional
{
	class IfStatement
	{
		public static void Main(string[] args)
		{
			int number = 2;
			if (number < 5)
			{
				Console.WriteLine("{0} is less than 5", number);
			}

			Console.WriteLine("This statement is always executed.");
		}
	}
}

When we run the program, the output will be:

2 is less than 5
This statement is always executed.

The value of number is initialized to 2. So the expression number < 5 is evaluated to true. Hence, the code inside the if block are executed. The code after the if statement will always be executed irrespective to the expression.

Now, change the value of number to something greater than 5, say 10. When we run the program the output will be:

This statement is always executed.

The expression number < 5 will return false, hence the code inside if block won’t be executed.

2. if-else statement: The if-else statement is used to execute one block of code if a condition is true, and another block of code if the condition is false. Here is the syntax:

if (condition)
{
    // code to be executed if the condition is true
}
else
{
    // code to be executed if the condition is false
}

Here is the example of If else statement,

using System;

namespace Conditional
{
	class IfElseStatement
	{
		public static void Main(string[] args)
		{
			int number = 12;

			if (number < 5)
			{
				Console.WriteLine("{0} is less than 5", number);
			}
			else
			{
				Console.WriteLine("{0} is greater than or equal to 5", number);
			}

			Console.WriteLine("This statement is always executed.");
		}
	}
}

When we run the program, the output will be:

12 is greater than or equal to 5
This statement is always executed.

Here, the value of number is initialized to 12. So the expression number < 5 is evaluated to false. Hence, the code inside the else block are executed. The code after the if..else statement will always be executed irrespective to the expression.

Now, change the value of number to something less than 5, say 2. When we run the program the output will be:

2 is less than 5
This statement is always executed.

The expression number < 5 will return true, hence the code inside if block will be executed.

3. switch statement: The switch statement is used to execute different blocks of code depending on the value of a variable. Here is the syntax:

switch (variable)
{
    case value1:
        // code to be executed if variable equals value1
        break;
    case value2:
        // code to be executed if variable equals value2
        break;
    // add more cases as needed
    default:
        // code to be executed if none of the cases are true
        break;
}

The switch statement evaluates the expression (or variable) and compare its value with the values (or expression) of each case (value1value2, …). When it finds the matching value, the statements inside that case are executed.

But, if none of the above cases matches the expression, the statements inside default block is executed. The default statement at the end of switch is similar to the else block in if else statement.

However a problem with the switch statement is, when the matching value is found, it executes all statements after it until the end of switch block.

To avoid this, we use break statement at the end of each case. The break statement stops the program from executing non-matching statements by terminating the execution of switch statement.

using System;
 
namespace Conditional
{
    class SwitchCase
    {
        public static void Main(string[] args)
        {
            char ch;
            Console.WriteLine("Enter an alphabet");
            ch = Convert.ToChar(Console.ReadLine());
 
            switch(Char.ToLower(ch))
            {
                case 'a':
                    Console.WriteLine("Vowel");
                    break;
                case 'e':
                    Console.WriteLine("Vowel");
                    break;
                case 'i':
                    Console.WriteLine("Vowel");
                    break;
                case 'o':
                    Console.WriteLine("Vowel");
                    break;
                case 'u':
                    Console.WriteLine("Vowel");
                    break;
                default:
                    Console.WriteLine("Not a vowel");
                    break;
            }
        }
    }
}

When we run the program, the output will be:

Enter an alphabet
X
Not a vowel

In this example, the user is prompted to enter an alphabet. The alphabet is converted to lowercase by using ToLower() method if it is in uppercase.

Then, the switch statement checks whether the alphabet entered by user is any of a, e, i, o or u.

If one of the case matches, Vowel is printed otherwise the control goes to default block and Not a vowel is printed as output.

4.Nested If Statement:

In C#, nested if statements are used to execute a set of instructions if the condition in the outer if statement is true, and then execute another set of instructions if the condition in the inner if statement is true as well.

Here’s an example of nested if statements in C#:

if (condition1)
{
    // code to execute if condition1 is true

    if (condition2)
    {
        // code to execute if condition1 and condition2 are true
    }
}
else
{
    // code to execute if condition1 is false
}

Here is the example of Nested if statement,

int x = 10;
int y = 20;

if (x == 10)
{
   Console.WriteLine("x is equal to 10");
   if (y == 20)
   {
      Console.WriteLine("y is equal to 20");
   }
   else
   {
      Console.WriteLine("y is not equal to 20");
   }
}
else
{
   Console.WriteLine("x is not equal to 10");
}

In this example, there are two variables ‘x‘ and ‘y‘. The outer if statement checks whether ‘x‘ is equal to 10. If it is, then the inner if statement checks whether ‘y‘ is equal to 20. If both conditions are true, then the program outputs the message “x is equal to 10” and “y is equal to 20”. If ‘y‘ is not equal to 20, then the program outputs the message “y is not equal to 20”. If ‘x‘ is not equal to 10, then the program outputs the message “x is not equal to 10”.

Leave a Comment

RSS
Follow by Email
YouTube
YouTube
LinkedIn
Share