Saturday, 25 January 2014

switch statement in C#

                                                                                                                                                                                            Previous....
                                                                                                                                                                                                            Next...
switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Syntax:

The syntax for a switch statement in C# is as follows:
switch(expression){
    case constant-expression  :
       statement(s);
       break; /* optional */
    case constant-expression  :
       statement(s);
       break; /* optional */
  
    /* you can have any number of case statements */
    default : /* Optional */
       statement(s);
}
The following rules apply to a switch statement:
  • The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
  • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
  • The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
  • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
  • When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
  • Not every case needs to contain a break. If no break appears, the flow of control will fall throughto subsequent cases until a break is reached.
  • switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. Nobreak is needed in the default case.

Flow Diagram:

switch statement in C#

Example:

using System;
 
namespace Switch_Case
{
  class Program
   {
     static void Main(string[] args)
      {
        int opt, num1, num2;
        float result;
 
        label:
 
        Console.WriteLine("\n\tMenu");
        Console.WriteLine("\nPress 1 for add");
        Console.WriteLine("Press 2 for subtraction");
        Console.WriteLine("Press 3 for multiplication");
        Console.WriteLine("Press 4 for Division");
  
        Console.Write("\n\nEnter first number:\t");
        num1 = Convert.ToInt32(Console.ReadLine());
 
        Console.Write("Enter second number:\t");
        num2 = Convert.ToInt32(Console.ReadLine());
 
        Console.Write("\nEnter your option:\t");
        opt = Convert.ToInt32(Console.ReadLine());
 
        switch (opt)
         {
           case 1:
               result = num1 + num2;
               Console.WriteLine("\n{0} + {1} = {2}", num1,                num2, result);
               break;
 
           case 2:
               result = num1 - num2;
               Console.WriteLine("\n{0} - {1} = {2}", num1,                num2, result);
               break;
           case 3:
               result = num1 * num2;
               Console.WriteLine("\n{0} * {1} = {2}", num1,                num2, result);
               break;
           case 4:
               result = (float)num1 / num2;
               Console.WriteLine("\n{0} / {1} = {2}", num1,                num2, result);
               break;
           default:
                   Console.WriteLine("\nInvalid option.                    Please try again.");
                   goto label;
         }
        Console.ReadLine();
      }
   }
}
When the above code is compiled and executed, it produces the following result:
       Menu

Press 1 for add
Press 2 for subtraction
Press 3 for multiplication
Press 4 for Division


Enter first number :       22
Enter second number :   8

Enter your option:          4
22 / 8 = 2.75 
                                                                                                                                           Previous....                                                                                                                                                           Next.....

If statement in C#

                                                                                                                                          Previous....
                                                                                                                                                      Next...


In this session we will discuss about

  • If statement
  • If else Statement
  • Difference b/w && and &
  • Difference b/w || and |
If statement check condition if the condition is true then it executed otherwise it goes in else part. lets take an example



syntax :-

The syntax of an if...else statement in C programming language is:
if(boolean_expression)
{
   /* statement(s) will execute if the boolean expression is true */
}
else
{
  /* statement(s) will execute if the boolean expression is false */
}
If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed.
C programming language assumes any non-zero and non-null values as true, and if it is either zero ornull, then it is assumed as false value.

Example:

using system
 
class programme 
{
   /* local variable definition */
   int a = 100;
 
   /* check the boolean condition */
   if( a < 20 )
   {
       /* if condition is true then print the following */
       console.writeline("a is less than 20\n" );
   }
   else
   {
       /* if condition is false then print the following */
       console.writeline("a is not less than 20\n" );
   }
   console.writeline("value of a is : %d\n", a);
 
   return 0;
}
When the above code is compiled and executed, it produces the following result:
a is not less than 20;
value of a is : 100

The if...else if...else Statement

An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind:
  • An if can have zero or one else's and it must come after any else if's.
  • An if can have zero to many else if's and they must come before the else.
  • Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax:

The syntax of an if...else if...else statement in C programming language is:
if(boolean_expression 1)
{
   /* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
   /* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
   /* Executes when the boolean expression 3 is true */
}
else 
{
   /* executes when the none of the above condition is true */
}

Example:

using System;  
namespace if_else_construct
{   class Program    
{      
static void Main(string[] args)       
{         
int opt, num1, num2;         
float result;           
label:           
Console.WriteLine("\n\tMenu");         
Console.WriteLine("\nPress 1 for add");        Console.WriteLine("Press 2 for subtraction");        Console.WriteLine("Press 3 for multiplication");        Console.WriteLine("Press 4 for Division");                      Console.Write("\n\nEnter first number:\t");         
num1 = Convert.ToInt32(Console.ReadLine());          Console.Write("Enter second number:\t");         
num2 = Convert.ToInt32(Console.ReadLine());          Console.Write("\nEnter your option:\t");         
opt = Convert.ToInt32(Console.ReadLine());           
if (opt == 1)          
{            
result = num1 + num2;            
Console.WriteLine("\n{0} + {1} = {2}", num1,num2, result);          
}         
else if (opt == 2)          
{            
result = num1 - num2;            
Console.WriteLine("\n{0} - {1} = {2}", num1,num2, result);          
}         
else if (opt == 3)          
{            
result = num1 * num2;            
Console.WriteLine("\n{0} x {1} = {2}", num1,num2, result);          
}         
else if (opt == 4)          
{            
result = (float)(num1 / num2);            
Console.WriteLine("\n{0} / {1} = {2}", num1,num2, result);         
}         
else          
{            
Console.WriteLine("Invalid option. Try again");           
goto label;          
}         
Console.ReadLine();                  
}    
}
}
When the above code is compiled and executed, it produces the following result:
        Menu

Press 1 for add
Press 2 for subtraction
Press 3 for multiplication
Press 4 for Division


Enter first number :       16
Enter second number :   5

Enter your option:          4

16 / 5 = 3.2 

What is difference between “&& ” , “& ”,"||" and "|" operators in C#?
1 - In the conditional statements:

When using the && operator the compilier uses short circuit logic, e.g.
it the first condition is false, the second one is not evaluated.
but when using the & operator the compilier evaluate both conditions even the first condition is false.

just like the & and && operator, the double Operator || is a "short-circuit" operator 
For example:

if(condition1 || condition 2 || condition 3)If condition1 is true, condition 2 and 3 will NOT be checked.

if(condition1 | condition 2 | condition 3)This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good performance boost by using them.

There is one big caveat, NullReferences or similar problems. For example:

if(class != null && class.someVar < 20)If class is null, the if-statement will stop after "class != null" is false. If you only use &, it will try to check class.someVar and you get a nice NullReferenceException. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad, but it's something to keep in mind.

2- There is a Second use of the | and & operator though: Bitwise Operations.

 | is the bitwise OR operator. Its used to operate on two numbers. You look at each bit of each number individually and, if one of the bits is 1 in at least one of the numbers, then the resulting bit will be 1 also. Here are a few examples:

A = 01010101
B = 10101010

A | B = 11111111
A & B = 00000000
A = 00000001
B = 00010000
A | B = 00010001
A & B = 00000000
A = 10001011
B = 00101100
A | B = 10101111
A & B = 00001000

                                                                                                                                          Previous....

                                                                                                                                                      Next...


C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...