Saturday 25 January 2014

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...


Comment in C#

                                                                                                                                Previous...
                                                                                                                                               Next.....





In this Tutorial, we will discuss
1. Single line comments
2. Multi line comments 
3. Introduction to XML documentation comments  



Single line Comments                       -   //
Multi line Comments                    -   /*  */
XML Documentation Comments      -   ///



Comments are used to document what the program does and what specific blocks or lines of code do. C# compiler ignores comments.

To Comment and Uncomment, there are 2 ways
1. Use the designer
2. Keyboard Shortcut: Ctrl+K, Ctrl+C and Ctrl+K, Ctrl+U

Note: Don't try to comment every line of code. Use comments only for blocks or lines of code that are difficult to understand 



                                                                                                                              Previous...
                                                                                                                                               Next.....

Friday 24 January 2014

Arrays in C#

                                                                                                                                     Previous...
                                                                                                                                                    Next.....

In this Tutorial, we will discuss
1. Arrays
2. Advantages and dis-advantages of arrays 



An array is a collection of similar data types.
using System;
class Program
{
    public static void Main()
    {
        // Initialize and assign values in different lines
        int[] EvenNumbers = new int[3];
        EvenNumbers[0] = 0;
        EvenNumbers[1] = 2;
        EvenNumbers[2] = 4;
        // Initialize and assign values in the same line
        int[] OddNumbers = { 1, 3, 5};
        Console.WriteLine("Printing EVEN Numbers");
        // Retrieve and print even numbers from the array
        for (int i = 0; i < EvenNumbers.Length; i++)
        {
            Console.WriteLine(EvenNumbers[i]);
        }
        Console.WriteLine("Printing ODD Numbers");
        // Retrieve and print odd numbers from the array
        for (int i = 0; i < OddNumbers.Length; i++)
        {
            Console.WriteLine(OddNumbers[i]);
        }
    }
}

Advantages: Arrays are strongly typed.

Disadvantages: Arrays cannot grow in size once initialized. Have to rely on integral indices to store or retrieve items from the array. 


                                                                                                                                   Previous...
                                                                                                                                                    Next.....

Thursday 23 January 2014

Datatype conversions in C#

                                                                                                                                         Previous.... 
                                                                                                                                                        Next...


In this Tutorial, we will discuss
1. Implicit conversions
2. Explicit Conversions
3. Difference between Parse() and TryParse() 



Implicit conversion is done by the compiler:
1. When there is no loss of information if the conversion is done
2. If there is no possibility of throwing exceptions during the conversion



Example: Converting an int to a float will not loose any data and no exception will be thrown, hence an implicit conversion can be done. 

Where as when converting a float to an int, we loose the fractional part and also a possibility of overflow exception. Hence, in this case an explicit conversion is required. For explicit conversion we can use cast operator or the convert class in c#.

Implicit Conversion Example
using System;
class Program
{
    public static void Main()
    {
        int i = 100;
        // float is bigger datatype than int. So, no loss of
        // data and exceptions. Hence implicit conversion
        float f = i;
        Console.WriteLine(f);
    }
}

Explicit Conversion Example


using System;
class Program
{
    public static void Main()
    {
        float f = 100.25F;

        // Cannot implicitly convert float to int.
        // Fractional part will be lost. Float is a
        // bigger datatype than int, so there is
        // also a possiblity of overflow exception
        // int i = f;

        // Use explicit conversion using cast () operator
        int i = (int)f;

        // OR use Convert class
        // int i = Convert.ToInt32(f);

        Console.WriteLine(i);
    }
}

Difference between Parse and TryParse
1. If the number is in a string format you have 2 options - Parse() and TryParse() 
2. Parse() method throws an exception if it cannot parse the value, whereas TryParse() returns a bool indicating whether it succeeded or failed.
3. Use Parse() if you are sure the value will be valid, otherwise use TryParse() 


                                                                                                                                         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...