logo codesdope

If and Else in C#


Till now, we have covered the basic parts like taking input, displaying output, doing some operations, etc. From this chapter, you are stepping into real coding.

Many times, we need to first see the conditions and accordingly make a decision. For example, if it is raining, we will take an umbrella otherwise not. Similarly, if a number is divisible by 2, it is even, otherwise, it is odd. Coming to a more programming-centric example, if a user is logged in then we will allow a certain feature, otherwise not.

if/else in C#

We use if/else to make these kinds of decisions in C#.

if Statement


Let's take an example first.

using System;

class Test
{
  static void Main(string[] args)
  {
    int a = 5;
    int b = 5;

    if(a == b)
    {
        Console.WriteLine("a and b are equal");
    }
  }
}
Output
a and b are equal

if (a==b)a==b is the condition of the if statement. Conditions are written inside '()'. Here, the condition is true. Since the condition is true, statements inside if will be executed.

{} after if represents the body of if. Whatever is written inside '{}' is a part of if.

So, the flow is that first the condition of if is checked and if it is true then statement(s) inside if are executed.

using System;

class Test
{
  static void Main(string[] args)
  {
    if(condition)
    {
        statement;
        statement;
        statement;
        statement;
        ...
    }
  }
}

else Statement


Let's take an example first. Consider that a chocolate costs 10 rupees and a candy costs 5 rupees. So, if you have at least 10 rupees, you can buy a chocolate, otherwise, you have to buy candy.

We can easily handle this kind of situations in C# using else statement. Let's take an example.

using System;

class Test
{
  static void Main(string[] args)
  {
    int a = 5;
    int b = 8;

    if(a == b)
    {
        Console.WriteLine("a and b are equal");
    }
    else
    {
        Console.WriteLine("a and b are NOT equal");
    }
  }
}
Output
a and b are NOT equal

In the same way as above, firstly, the condition in if will be checked and since it is false (5 and 8 are not equal), so statements in else are executed. It is that simple.

using System;

class Test
{
  static void Main(string[] args)
  {
    if(condition)
    {
        statement;
        statement;
        ...
    }
    else
    {
        statement;
        statement;
        ...
    }
  }
}

If the condition is true, statements in if are executed. Otherwise, statements in else are executed.

Let's take one more example.

using System;

class Test
{
  static void Main(string[] args)
  {
    int n;
    Console.WriteLine("Enter a number");
    n = Convert.ToInt32(Console.ReadLine());
    if(n%2 == 0)
    {
        Console.WriteLine("Number is even");
    }
    else
    {
        Console.WriteLine("Number is odd");
    }
  }
}
Output
Enter number
5
Number is odd

For a number to be even, it must be divisible by 2. This means that it should give a remainder 0 if divided by 2.

We entered 5 here and the value of n%2 i.e., 5%2 is 1. So, the statement in the body of else gets executed and "Number is odd" got printed on the screen.

Decision making (if/else) is an integral part of any programming language. It has multiple applications in various fields like robotics and many others. Let's consider an example that a person is eligible to vote in an election only if his age is more than 18 years.

using System;

class Test
{
  static void Main(string[] args)
  {
    int age;
    Console.WriteLine("Enter your age");
    age = Convert.ToInt32(Console.ReadLine());
    if(age >= 18)
    {
        Console.WriteLine("You are 18+");
        Console.WriteLine("Eligible to vote");
    }
    else
    {
        Console.WriteLine("You are not yet 18");
        Console.WriteLine("Not eligible to vote");
    }
  }
}
Output
Enter your age
20
You are 18+
Eligible to vote

In this example, since the user entered the 20 for the age, which is greater than 18, so the condition age >= 18 became true. Therefore, the statements in the body of if got executed. If the user enters the age less than 18, then the condition age >= 18 will become false and the statements in the body of else statement will be executed.

Nested if/else Statements


We can also use if or else inside another if or else statements.

To understand this, let's see an example to print whether a number is the greatest or not by using one if inside another if.

using System;

class Test
{
  static void Main(string[] args)
  {
    int x = 4, y = 3, z = 5;

    if(z>x)
    {
        if(z>y)
        {
            Console.WriteLine("z is the greatest number");
        }
    }
  }
}
Output
z is the greatest number

In the above example, the first expression i.e., if(z>x) is true. So, the statements enclosed within the curly brackets {} of the first if will be executed.

Within the curly brackets of the first if, the first statement is if(z>y).

Since this condition is also true, the statement Console.WriteLine("z is the greatest number") within the curly brackets of this if will be executed.

So, first, we checked if z is greater than y or not. If it is, then we compared it with y.

Thus, a if inside another if is just like another statement. It will be executed just like any other statements.

using System;

class Test
{
  static void Main(string[] args)
  {
    int x = 4, y = 3, z = 5;

    if(x>y)
    {
        if(x>z)
        {
            Console.WriteLine("x is the greatest number");
        }
        else
        {
            Console.WriteLine("x is not the greatest number");
        }
    }
    else
    {
        Console.WriteLine("x is not the greatest number");
    }
  }
}
Output
x is not the greatest number

Here the condition x > y is true. So the statements enclosed within the curly brackets { } of the first if will be executed. Within the curly brackets, the first line i.e. if(x > z) will be executed first. Since this condition is false, the statement Console.WriteLine("x is the greatest number"); within the curly brackets of this if will not be executed. So, the statement of its corresponding else (i.e. the inner else) Console.WriteLine("x is not the greatest number"); will be executed.

Here, the condition inside if will be true only if both (x > y) and (x > z) are true. If that is the case, then x will be the greatest number otherwise not.

else if Statements


Many times we fall in situations when if and else are not sufficient. For example, if you have 5 rupees then you will buy a candy, or if you have 10 rupees, then a chocolate and if more than 100, then a cake. Thanks to C#, because it provides another tool else if to get this done.

Consider this example to find the greatest among the three numbers.

using System;

class Test
{
  static void Main(string[] args)
  {
    int x = 4, y = 5, z = 1;

    if((x>y) && (x>z))
    {
        Console.WriteLine("x is the greatest number");
    }
    else if((y>x) && (y>z))
    {
        Console.WriteLine("y is the greatest number");
    }
    else
    {
        Console.WriteLine("z is the greatest number");
    }
  }
}
Output
y is the greatest number

We give condition in else if also. First, the condition of if will be checked. If it is false, then condition of else if will be checked, and if that is also false then else will be executed.

In the above example, we are given three numbers x, y and z and have to find the highest among them.

For that, first, we will compare the first number with the other two i.e., x with both y and z. Now, if the condition (x>y && x>z) is true (if both are true, meaning x is the greatest), then the statements enclosed within the curly brackets {} of the first if condition will be executed. If not so, then it will go to else if and check for (y>x && y>z). If this condition is true, then the corresponding statements will be executed, otherwise, it will go to else.

Let's take one more example.

using System;

class Test
{
  static void Main(string[] args)
  {
    char grade = 'A';

    if( grade == 'A' )
    {
        Console.WriteLine("Excellent !");
    }
    else if(grade == 'B')
    {
        Console.WriteLine("Outstanding !");
    }
    else if(grade == 'C')
    {
        Console.WriteLine("Good !");
    }
    else if(grade == 'D')
    {
        Console.WriteLine("Can do better");
    }
    else if(grade == 'E')
    {
        Console.WriteLine("Just passed");
    }
    else if(grade == 'F')
    {
        Console.WriteLine("You failed");
    }
    else
    {
        Console.WriteLine("Invalid grade");
    }
  }
}
Output
Excellent !

First, the condition of if is checked. If it is true, then only the statements inside that if are executed, otherwise the compiler checks the condition inside else if. If it is true, then its body is executed, otherwise next else if is checked. If none of them are true then else is executed.

Thus, the format of else if is:

using System;

class Test
{
  static void Main(string[] args)
  {
    if(condition)
    {
        statement;
        statement;
        ...
    }
    else if(condition)
    {
        statement;
        statement;
        ...
    }
    else if(condition)
    {
        statement;
        statement;
        ...
    }
    else if(condition)
    {
        statement;
        statement;
        ...
    }
    ...
    ...
    else
    {
        statement;
        statement;
        ...
    }
  }
}

If there is a single statement inside if, else or else if, we can skip the braces ({}). Let's look at an example.

using System;

class Test
{
  static void Main(string[] args)
  {
    int a = 10;

    if(a == 30)
        Console.WriteLine("It is 30");
    else if(a == 10)
        Console.WriteLine("It is 10");
    else if(a == 5)
        Console.WriteLine("It is 5");
    else
        Console.WriteLine("None");
  }
}
Output
It is 10

As you can see in the above example that a single statement is considered as a part of if, else and else if without any braces ({}).

Switch Case


Normally, if we have to choose one case among many choices, nested if-else is used. But if the number of choices is large, switch..case is a better option as it makes our code more neat and easier to read.

Let's have a look at its syntax.

switch(expression)
{
    case constant1:
        statement(s);
        break;
    case constant2:
        statement(s);
        break;
/* you can give any number of cases */
    default:
        statement(s);
}

In switch...case, the value of the expression enclosed in the brackets ( ) following switch is checked. If the value of the expression matches the value of the constant in any case, the statement(s) corresponding to that case will be executed.

If the expression does not match any of the constant values, then the statements corresponding to default are executed.

Let's look at an example.

using System;

class Test
{
  static void Main(string[] args)
  {
    char grade = 'B';

    switch (grade)
    {
        case 'A':
            Console.WriteLine("Outstanding!");
            break;
        case 'B':
            Console.WriteLine("Excellent!");
            break;
        case 'C':
            Console.WriteLine("Good!");
            break;
        case 'D':
            Console.WriteLine("Can do better!");
            break;
        case 'E':
            Console.WriteLine("Just passes!");
            break;
        case 'F':
            Console.WriteLine("Failed!");
            break;
        default:
            Console.WriteLine("Invalid Grade!");
            break;
    }
  }
}
Output
Excellent!

In this example, the value of grade is 'B'. So, the case with the value of constant as 'B' will be executed and Excellent! will be printed. Then break statement will terminate the switch without checking the rest of the cases. This is how it works.

break is used to terminate the execution of switch and come out of the switch statement.

Let's see another example where the value of the expression is an integer.

using System;

class Test
{
  static void Main(string[] args)
  {
    int i = 2;

    switch (i)
    {
        case 1:
            Console.WriteLine("Number is 1");
            break;
        case 2:
            Console.WriteLine("Number is 2");
            break;
        default:
            Console.WriteLine("Number is neither 1 nor 2");
            break;
    }
  }
}
Output
Number is 2

Another form of if else - Ternary Operator


We can also judge the condition using a ternary operator. Ternary operator checks whether a given condition is true and then evaluates the expressions accordingly. It works as follows.

condition ? expression1 : expression2;

If the condition is true, then expression1 gets evaluated, otherwise expression2 gets evaluated.

ternary operator in C#

using System;

class Test
{
  static void Main(string[] args)
  {
    int age;
    Console.WriteLine("Enter age");
    age = Convert.ToInt32(Console.ReadLine());

    var s = (age > 18) ? "eligible to vote" : "not eligible to vote";

    Console.WriteLine(s);
  }
}
Output
Enter age
5
not eligible to vote

Here, if the condition (age > 18) is true, then expression1 i.e., "eligible to vote" will be assigned to the variable s, otherwise, expression2 i.e., "not eligible to vote" will be assigned to s. Since the value of age that we entered (10) is less than 18, therefore expression2 is assigned to the variable s.

Let's see another example in which we want to find the greater among two numbers.

using System;

class Test
{
  static void Main(string[] args)
  {
    int num1 = 4, num2 = 5, num;

    num = (num2 > num1) ? num2 : num1;

    Console.WriteLine(num);
  }
}
Output
5

In this example, if the condition (num2 > num1) is true, then num2 i.e., 5 will get assigned to num, otherwise, num1 i.e., 4 will get assigned to num. In our case, the values of num1 and num2 are 4 and 5 respectively. Thus, the condition num2 > num1 is true and the value of num2 i.e., 5 got assigned to num and so 5 got printed.


Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.