Pages

Monday 8 September 2014

Conditional Construct in C# Part 4



      In this post we explain about all four conditional construct with the help of examples If you are reading our C# posts first time we will suggest you to read our previous post to better understand the concept, if you already had or you know the concept and want to know about conditional construct then start reading. But first we should understand about Boolean value.

Boolean Variable and Operator

       C# provide a data type called bool. A variable of bool data type can only hold two value either false or true. For example:

bool car;
car = false;
Console.WriteLine(car); // print False on console screen

    In the preceding example a variable of bool data type car is declared which has been assigned a value false, and WriteLine method of the console class is used to print the value of car variable.
    
    Similarly a Boolean operator is an operator that evaluate a statement whose result is either true or false. For example:

int a, b;
bool result;
a = 10;
b = 8;
result = (a != b);//evaluate the expression on right and assign its result to the variable on left
Console.WriteLine(result);// print the value of result on console screen

    In the preceding example, we have declared two variable a, and b of integer data type and assigned values 10 to a, and 8 to b. In the fifth line we are checking whether the value of variable a is equals to the value of variable b, to check it we are using a comparison operator not equals to that can only have two values either true or false, and then assigning the outcome to the result variable of Boolean data type that again can have only two value true, or false.


NOTE: In the preceding example the result variable is of Boolean data type any other data type will not support this statement and will give error because the expression will return a Boolean value and only a Boolean variable can store bool value true or false.
                      
     
     To fully understand the concept of conditional constructs you should have the knowledge of data types and variables. Click here to read about it in our post using various operators in C #.
  

Conditional construct

  
   Conditional construct or conditional statement are used to make decision in your program consider an example of a traffic light you will stop your car when the light is red and go when it is green, so whether you will stop your car or go depend on the state of traffic light whether it is red or green. Whenever you find this type of situation in coding you can use conditional construct. 
The conditional construct will execute a particular block of statement based on the condition you provide, the condition are of Boolean value , means an expression will return either true or false value.
There are four types of conditional construct in C#:
  1. if Statement.
  2. if….else statement.
  3. Nested if…else statement.
  4. Switch case statement.


The if statement

   

    The if statement is followed by a BooleanExpression if the BooleanExpression evaluates to true the statement in the if the block will be executed but if the BooleanExpression evaluates to false, the execution of code will continue with whatever code is after that if block.
The syntax of if statement:

if (BooleanExpression)
{
    Statement1;
    Statement2;   
}

     If there is only a single statement in your if block it is not necessary to enclose the if block within curly braces (delimiters). Example:

if (BooleanExpression)
             Statement1;  //Single statement

This code will work because it has only one statement in the if block.

The if…else statement          

    The if...else statement is same as the if statement but with the addition of an else block. If the BooleanExpression in the if…else block evaluate to false the statement in the else block will get executed. The syntax for if…else construct or statement is:

if (BooleanExpression)
{
   Statement1;
}
else
{
   Statements1;
}

Consider an example where you want to accept a number from the user and check if it’s an even number or odd, and print the result on the console screen. The following code show you how to do this using the if…else construct:

int a;

Console.WriteLine("Enter a number");

a = Convert.ToInt32(Console.ReadLine());

if ( a % 2 == 0 )
{
Console.WriteLine("You Entered an Even Number");
}
else
{
Console.WriteLine("You Entered an Odd Number");

}

       So, in the preceding code we have declared a variable a of integer data type then we used the ReadLine method of the console class to accept input from user on line 3 the ReadLine method by default accept data in string format so we used the Convert.ToInt32 method to convert it in integer format for our integer variable a in the BooleanExpression of the if block we use the modulus operator to check if the remainder is equals to 0 after dividing the variable by 2 if it evaluates to true the code in the if block will get executed if not the else block will get executed. See the output of console screen below:





 The nested if…else Statement

    
   The if… else statement can also be nested inside each other. Means you can write an if…else statement inside an if block or the else block. Check the syntax below:

if (BooleanExpression)
{
    Statement;

    if (BooleanExpression)
    {
      Statement;
    }
    else
    {
      Statement;              
    }

    Statement;
}
else
{
    Statement;
}

     For example think of a situation where the user want to check his grade, for this he have to input his name and student id if the input he gave was right  then the grade will be shown on the console screen else “Invalid Name Or ID” will be shown. For this he have to write the following code:

string name, studentId;

Console.WriteLine("Please Enter Your Name");

name = Console.ReadLine();

Console.WriteLine("Please Enter Your Student ID");

studentId = Console.ReadLine();

if (name.ToUpper() == "ALEX")
{
   if (studentId == "i396")
   {
      Console.WriteLine("Congratulations You Got Grade A");
   }
   else
    {
      Console.WriteLine("Invalid Name or ID");
    }
}


      In the preceding code we accept the name and student id of the user and store it in the name and studentId variable which are of string data type note that the ReadLine method accept string data type by default  so we don’t have to convert the data type of our variables. In the sixth line we are using ToUpper() method to convert the user input into uppercase letter, this small things are really important in your code because you don’t know how the user will type his name to fix this error we used the ToUpper()  method. Then you can see that how use the second if…else statement to validate the studentId. So this is how you can use nested if…else block in this type of situation where you have to evaluate multiple condition in your code. See the output below:



And the invalid input:



But this code can also be written with logical operators check the code below:

string name, studentId;

Console.WriteLine("Please Enter Your Name");

name = Console.ReadLine();

Console.WriteLine("Please Enter Your Student ID");

studentId = Console.ReadLine();

if ((name.ToUpper() == "ALEX")&&(studentId == "i396"))
{
             
    Console.WriteLine("Congratulations You Got Grade A");
}
else
{
    Console.WriteLine("Invalid Name or ID");
}
    
     So in the preceding code we used the logical operator to check both condition in the same BooleanExpression, and it will give you the same result. To read about logical operators click here

The switch…case Statement

        
       Think of a situation where have to evaluate a variable for multiple values, like where a user want to open a particular hotel room based on the room number, if you used nested if…else you have write multiple if…else block and it will be time consuming and not a good coding practice. In this type of situation you can use switch…case construct. The switch case construct is used where you have evaluate a variable for multiple values the syntax of switch case is:

switch (controllingExpression)
{
     case constantExpression:
         statements;
         break;
    
     case constantExpression:
         statements;
         break;
    
     case constantExpression:
         statements;
         break

     default:
         statements;
         break;
}

     In the switch case statement the controllingExpression is only evaluated once, the controllingExpression is the variable you want to evaluate. If one of the constantExpression match with the value given in the variable means the controllingExpression the control will be passed to the statements of that matched case. The break statement is used to stop the switch…case construct to prevent the execution of remaining case structures. If none of the constantExpression matched with the value of the controllingExpression the statement under the default statement will run.  

Let’s write the code on hotel room example were the user want to open a room based on its room number:

int roomNumber;
Console.WriteLine("Enter your room number");
roomNumber = Convert.ToInt32(Console.ReadLine());
switch (roomNumber)
{
       case 105:
       Console.WriteLine("Wrong room");
       break;
       case 106:
       Console.WriteLine("Sorry for disturbance, wrong room");
       break;
       case 107:
       Console.WriteLine("Welcome to your room");
       break;
       case 108:
       Console.WriteLine("Hotel staff room");
       break;

       default:
       Console.WriteLine("Sorry Invalid room number");
       break;
}

Check the outputs below:

                        The user entered 106.

                        The user entered 107.

                        The user entered 200.

The switch…case statement rules 


There are some rules you should remember and follow while working with switch…case construct:
  1.        The constant expression must be unique, means two constantExpression can’t have the same value.
  2.          You can’t use every data type for the switch…case controllingExpression. Only int, char, or string can be used for any other data type like decimal and float you have to use if statement.
  3.           If you are using int data type you have to write 5, for char data type you have to write ‘5’, and for string data type you have to write “5”. If you write 4 for string data type it will give you an error it must be written like “4”.


So start coding use this concept in your code ask me about any problem you have while using this concepts on your program in comments. Read our previous posts on C# 

Previous post                                                                                                                               Next post