Thursday, 24 February 2011

Chapter 7 Selection Statements

A selection statement causes the program control to jump to another part of the program depending on a condition. Following are the selection statement available to you under C#

  1. if
  2. else
  3. switch
  4. case
  5. default

if-else statement

The if statement selects a statement for execution based on the value of a Boolean expression.
Lets check this fact out in the following example

using System;

/**
 * Author       : vblord
 * Date         : 10/03/2011
 * Description  : Check to see if the user is vegetarian or non-vegetarian and print
 *                   an appropriate message. Shows the usage of if-else
 *                
 */
namespace HelloWorld
{
    class ifelseexample
    {
        static void Main(string[] args)
        {
            Console.Write("Enter are you a vegetarian (Y/N) : ");
            char veg = char.Parse(Console.ReadLine());
            if (veg == 'Y'){
                Console.WriteLine("So you are a vegetarian, then you must love spinach");
            }
            else {
                Console.WriteLine("Aha so you are a non-vegetarian , you must like some chicken");
            }
            
            Console.ReadKey(false);
        }
    }
}


This is the output according to the user given choice

If there is more than one statement associated with the TRUE condition or FALSE condition then we must use {} to keep them in a block, because by default if only recognizes the first statement after if--elseas the statement to execute. If there is only a single line then you may or may not use the {} as per your wishes.

Nested if

Some time we require more than one condition to be true. For a statement to execute and more than one else clause. Lets look at the example below
using System;

/**
 * Author       : vblord
 * Date         : 10/03/2011
 * Description  : this is an example of nested if which firstly checks if the input 
 *                 value is an alphabet and then checks if it is lower case or uppercase
 *                
 */
namespace HelloWorld
{
    class nestedifexample
    {
        static void Main(string[] args)
        {
            Console.WriteLine("NESTED IF EXAMPLE");
            Console.Write("Enter a Any Alphabet : ");
            char c = (char)Console.Read();
            if (Char.IsLetter(c))
            {
                if (Char.IsLower(c))
                {
                    Console.WriteLine("The input is lowercase alphabet.");
                }
                else
                {
                    Console.WriteLine("The input is an uppercase alphabet.");
                }
            }
            else
            {
                Console.WriteLine("Sorry this is not an alphabet.");
            }
            
            Console.ReadKey(false);
        }
    }
}
This program asks the user for an input and the first condition to be checked is that the input should be an alphabet if it is not then it jumps to the outer else, if it is true then it checks the second if to find out the character is an uppercase or lowercase alphabet.
Sample Output 1
Sample Output 2


Sometimes nested if is not exactly what we want because there are multiple conditions to check. In such a case we can use the if-else-if structure to extend the use of this statement. Again it is much simpler to explain with the help of an example.

using System;

/**
 * Author       : vblord
 * Date         : 10/03/2011
 * Description  : this is an example of else-if construct which calculates grades of student        
                    based on his percentage
 *                 
 *                
 */
namespace HelloWorld
{
    class ifelseifexample
    {
        static void Main(string[] args)
        {
            Console.WriteLine("ELSE-IF EXAMPLE");
            Console.Write("Enter your marks in Hindi : ");
            int hindi = int.Parse(Console.ReadLine());
            Console.Write("Enter your marks in Computer : ");
            int comp = int.Parse(Console.ReadLine());
            Console.Write("Enter your marks in English : ");
            int eng = int.Parse(Console.ReadLine());
            int tot = hindi + eng + comp;
            float per = tot / 3;
            char grade=' ';
            if (per >= 90)
                grade = 'A';
            else if (per >= 75 && per < 90)
                grade = 'B';
            else if (per >= 60 && per < 75)
                grade = 'C';
            else if (per >= 45 && per < 60)
                grade = 'D';
            else if (per < 45)
                grade = 'F';
            Console.WriteLine("Total Marks are {0} your % is {1} your Grade is {2}", tot, per, grade);
            
            Console.ReadKey(false);
        }
    }
}
Sample Output
The above mentioned program calculates the total and percentage marks after accepting input of three subjects. then based on a set of conditions it gives the student a grade. In every case only one condition can be true and the student can get only one grade, some may argue this can be done by nested if but my reason for using else-if construct for this program is simplify it.

Switch statement

The switch statement is a control statement that handles multiple selections and enumerations by passing control to one of the case statements within its body . Control is transferred to the case statement which matches the value of the switch. The switch statement can include any number of case instances, but no two case statements can have the same value. Execution of the statement body begins at the selected statement and proceeds until the break statement transfers control out of the case body. A jump statement such as a break is required after each case block, including the last block whether it is a case statement or a default statement. With one exception, (unlike the C++ switch statement), C# does not support an implicit fall through from one case label to another. The one exception is if a case statement has no code. If no case expression matches the switch value, then control is transferred to the statement(s) that follow the optional default label. If there is no default label, control is transferred outside the switch.
using System;

/**
 * Author       : vblord
 * Date         : 10/03/2011
 * Description  : this is an example of switch case construct it takes a number from 1-7 and prints the
 *                 corresponding day of the week
 *                 
 *                
 */
namespace HelloWorld
{
    class ifelseifexample
    {
        static void Main(string[] args)
        {

            myDayOfWeek();
            Console.ReadKey(false);
        }

        static void myDayOfWeek()
        {
            Console.WriteLine("switch case example");
            Console.Write("Enter day of the week in numbers from 1-7 : ");
            int day = int.Parse(Console.ReadLine());
            string answer = "";
            switch(day)
            {
                case 1:
                    answer = "Monday";
                    break;
                case 2:
                    answer = "Tuesday";
                    break;
                case 3:
                    answer = "Wednesday";
                    break;
                case 4:
                    answer = "Thursday";
                    break;
                case 5:
                    answer = "Friday";
                    break;
                case 6:
                    answer = "Saturday";
                    break;
                case 7:
                    answer = "Sunday";
                    break;
                default:
                    answer = "Are you joking mate";
                    break;
            }
            Console.WriteLine("You entered {0} and the day of the week is {1}", day, answer);
            
        }
    }
}

Sample Output
These were the selection statement available to you in C#, in our next chapter we will look into few more statements provided by C#

No comments:

Post a Comment