C# Conditional Statement: With Example

07:21
Conditional Statements and Loops are most important aspect of any programming language. Every programming language offer same set of conditional structure. IF Statement, IF...ELSE Statement, Nested IF Statement, Switch Statement. Beside this C# also provide loop statement.

Also Read:  Type Conversion Or Type Casting In C# With Examples

Conditional statement control for flow of program based on certain condition. Where as Loop also control program flow but they repeats the programming statement till the condition remains true.

Condition Statement:

First we will start with conditional statements. For understanding this statement you first need to understand basic flow of Conditional statement. Here is basic flow we have tried to explain diagrammatically. 

IF Statement:

If statement is simplest conditional statement that we use in day to day life. Programming becomes easy when we compare this things with real world scenario. We take day to day decision using this type thinking only. 
Example: If I will buy xyz thing then what will be it's cost. If it cost below $20 then only I will buy this thing.

In programming also we need to avoid certain conditions to get fulfill. Here is syntax for simple if statement:
if(boolean_expression)
{
 //this statement will only execute when boolean_expression is true.
}
Let's take above situation and covert it into programming scenario.
using System;
using System.Collections.Generic;
namespace Type_of_if
{
    class Person
    {
        static void Main(string[] args)
        {
            int expense = 10;// You have 20$ at your exposure
            if (expense > 20)// Check if expense is more then 20$ then you can purchase more items
            {
                Console.WriteLine("You cannot buy more..........");
            }
            Console.WriteLine("You can buy more..........");
        }
    }
}

Output:

 You can buy more..........

In above example class person act as real person that is in supermarket and have amount of 20$ to spend for his daily needs. In this if condition, person check for expense variable every time he buy any item i.e. total sum is less then $20 if it more then that then he will not buy. If you change value of variable expense to greater then 20 say 22 then will show you output as:

You cannot buy more..........

IF.......ELSE Statement:

In above example we have only evaluated one condition. If this... but in real life situation we always check for if not this........ then that. Suppose that person need some more cash for buying more stuff but have used his entire $20 amount. Then what to do? Everyone have debit card with us now days. So if person runs out of money then So this condition in above condition can be integrated as follows:

using System;
using System.Collections.Generic;

namespace Type_of_if
{
    class Person
    {
        static void Main(string[] args)
        {
            int expense = 22;// This is your expense

            if (expense < 20)// Check if expense is less then 20$ then you can purchase more items
            {
                Console.WriteLine("You have still money left...........");
            }
            else// if expense is more then $20 then you can use debit card
            {
                Console.WriteLine("You have to use debit card now.....");
            }
        }
    }
}

Output
You have to use debit card now.....

IF.......ELSE....IF

In above condition if person have more then two choices to make then we can use IF.....ELSE....IF. It is also known as IF...ELSE ladder. Let's say person have $20 cash and debit card and vouchers for the specific store, where is is doing shopping. Then his preference will be if amount is less then $20 then spend $20 if less then $ 30 voucher worth of $30 and still if bill is more then that but less then $50 he will use debit card having balance $50. But we always make our case safe. So if amount is more then $50 will say you have to use two option combine.

Here is programmatic implementation of above condition:

using System;
using System.Collections.Generic;
namespace Type_of_if
{
    class Person
    {
        static void Main(string[] args)
        {
            int expense = 15;// This is your expense
            if (expense < 20)// Check if expense is less then 20$ then you can purchase more items
            {
                Console.WriteLine("You have used money ...........");
             
            }
            else if(expense <30)
            {
                Console.WriteLine("You vouchers are used ");
             
            }
            else if(expense < 50)
            {
                Console.WriteLine("You have used your debit card....... ");
            }
            else
            {
                Console.WriteLine("You have to use all of them..... ");
            }
        }
    }
}

Also Read: C# Data Type In Detail

SWITCH Statement: 

Switch statement also work like if...else..if statement that we saw above. You can also write the above program using switch statement. But I'll take different example this time. We all know grading system in school that we used to get out exam score. Will write simple program in Switch case for the same.

First you need to learn basic syntax for switch statement :

switch(expression) {
   case constant-expression  :
      statement;
      break;
   case constant-expression  :
      statement(s);
      break;
   default :
   statement(s);
}

Program is as follows:
using System;
using System.Collections.Generic;
namespace Type_of_if
{
    class Person
    {
        static void Main(string[] args)
        {
            char result;
            Console.WriteLine("Enter Your Grade from A OR B OR C OR D OR F");
            result = Convert.ToChar(Console.ReadLine());
         
            switch (result)
            {
                case 'A':
                    Console.WriteLine("You have got 75% and above");
                    break;
                case 'B':
                    Console.WriteLine("You have got less then 75% ");
                    break;
                case 'C':
                    Console.WriteLine("You have got 60% and above");
                    break;
                case 'D':
                    Console.WriteLine("You have got less then 60% and above");
                    break;
                case 'F':
                    Console.WriteLine("Better Luck Next Time");
                    break;
                default:
                    Console.WriteLine("Invalid input");
                    break;
            }
        }
    }
}
The program is self explanatory. But you need to know if you input alphabet small or any other then A OR B OR C OR D OR F you will get out put as invalid input. Hence we can say switch case is case sensitive. You can run it and check by your self. 

The?:operator OR Ternary operator:

This is popularly known as ternary operator. It can be used in place of IF..... ELSE statement. It works same as IF... ELSE. 

Syntax:

Exp1 ? Exp2 : Exp3;


In this operator ? is conditional operator. And expression one is evaluated as boolean expression. Let's see simple example.
using System;
using System.Collections.Generic;
namespace Type_of_if
{
    class Person
    {
        static void Main(string[] args)
        {
            int a = 10;
            string classfy;
            classfy = (a > 0) ? "positive" : "Negative";
            Console.WriteLine("Variable A is classify as "+classfy+" number");
        }
    }
}

Output:
Variable A is classify as positive number
In above example we have just classify if variable a having value 10 is positive or negative.

So here all conditional operators/ statements are explained with example. We are trying out best to make you understand program in laymen term. If you still have any doubt or any query feel free to comment below. Thanks fro reading.

Share this

CEO and Admin of TechnoDiscover And Nothing Like Everything
Bcom From Mumbai University
Pursuing MCA From Mumbai University

Related Posts

Previous
Next Post »