Monday, 12 January 2015

Datatype Conversion

1. Implicit conversion and explicit conversion


a) Implicit Conversion:

Implicit conversion is done by the compiler.
1). When there is no loss of information and the size of target type is larger than the size of previous type.
2).If there is no possibilities of throwing the exception during the conversion

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

Size of int is -2,147,483,648 to 2,147,483,647 and size of float is -3.4 × 1038 to +3.4 × 1038

Exp:


  1. using System;  
  2. class implicitDemo  
  3. {  
  4.    public static void Main()  
  5.    {  
  6.        int i = 100;  
  7.        float j=i;  
  8.       Console.WriteLine(j);  
  9.    }  
  10. }  

Implicit conversion output screenshots
Fig: Screenshots of Output

b). Explicit Conversion :


When converting a float type to int type, we loose fractional part and also possibilities of overflow exception. Hence, in this case an Explicit conversion is reqiured. For explicit conversion we can use cast operator or the convert class

Example:

1.
  1. using System;  
  2. class ExplicitDemo  
  3. {  
  4.    public static void Main()  
  5.   {  
  6.       float f = 10987452135547895640.256F;  
  7.       float fi = 2558679458632566.1296F; 
  8.   
  9.     int i = f;    
  10.     int j = fi; 
  11.   
  12.     Console.WriteLine("{0}{1}", i,  j);  
  13.   }  
  14.   
  15. }  

  On compiling the above code it gives error:
Fig: Screenshots of Output

2. Modified code

  1. using System;  
  2. class ExplicitDemo  
  3. {  
  4.    public static void Main()  
  5.   {  
  6.       float f = 100.256F;  
  7.       float fi = 256.1296F  
  8.   
  9.     int i = (int)f;    // Type cast Operator  
  10.     int j = Convert.ToInt32(fi);   //using convert class  
  11.   
  12.     Console.WriteLine("{0}{1}", i,  j);  
  13.   }  
  14.   
  15. }  

Output of explicit conversion
Fig: Screenshots of Output


2. Parse() and TryParse()


If the number is in string format you have two option to convert them into another type one is Parse() and other is TryParse().

Parse() method throws an exception if it cannot parse the value, whereas TryParse() returns a bool indicating weather it succeeded or failed.

Use Parse() if you sure the value will be valid otherwise use TryParse().


Example 1. simple parse program

  1. using System;  
  2. class ParseDemo  
  3. {  
  4.     public static void Main()  
  5.     {  
  6.         string strNumber = "100";  
  7.   
  8.         int i = int.Parse(strNumber);  
  9.   
  10.         Console.WriteLine(i);  
  11.     }  
  12. } 

Parse() method output
Fig: Output of Parse() method

Example 2. Parse() method throw an Exception if it cannot parse the value

  1. using System;  
  2. class ParseDemo  
  3. {  
  4.     public static void Main()  
  5.     {  
  6.         string strNumber = "100Sa";  
  7.   
  8.         int i = int.Parse(strNumber);  
  9.   
  10.         Console.WriteLine(i);  
  11.     }  
  12. }  

Unhandled Exception of Parse method
Fig: Unhandled Exception


Example 3. TryParse() returns bool in case of failure

  1. using System;  
  2. class ParseDemo  
  3. {  
  4.     public static void Main()  
  5.     {  
  6.         string strNumber = "100San";  
  7.   
  8.         int Result = 0;  
  9.   
  10.         bool IsConversionSucessful = int.TryParse(strNumber, out Result);  
  11.   
  12.         if(IsConversionSucessful)  
  13.         {  
  14.             Console.WriteLine(Result);  
  15.         }  
  16.   
  17.         else  
  18.         {  
  19.             Console.WriteLine("Please enter a valid Number");  
  20.         }  
  21.     }  
  22. }  

Fig: Output of TryParse()

Sunday, 11 January 2015

Nullable Types(?) and Null Coalescing Operator(??)

1.Nullable Types '?' : 

In C-sharp Types are divided into 2 categories

Value Types: Int, float, double, struct, enums etc
Reference Types: Interface, class, delegates, arrays etc

Nullable type is to provide null value to any type.

By Default value types are non-nullable to make them nullable use "?"

Exp:

int i = 0;              // i is non nullable because data type of i is int, so i cannot set to null .
int i = null;         // it will generate compiler error

so we use "?" to provide null value to 'i'

Syntax:
int? i = null;

Exp:
  1. {  
  2.      static void Main()  
  3.      {  
  4.           string name = null;  
  5.           int i= null;  
  6.           int? i = null;  
  7.      }  
  8. } 

In Line 4 we initialize name to null since it is legal because string is the reference type variable.
In Line 5 we initialize i to null it will generate a compiler error because i is Value type. So, we use "?" in line 6 to make it legal and nullable.


2.Null Coalescing Operator '??' :

This is used to define a default value for nullable types or reference type it return the left hand operand if the operand is not null otherwise it return the right hand operand.

Syntax:
              x=y??1;
Exp:

  1. class Test
  2. {
  3.    static void Main()
  4.    {
  5.       int availableTickets;
  6.       int? ticketOnSale = null;

  7.          if(ticketOnSale == null)
  8.          {
  9.             availableTickets = 0;  // Assign a value when it satisfy null condition

  10.          }

  11.          else
  12.          {
  13.             availableTickets = (int)ticketOnSale;
             }

  14.          Console.WriteLine(availableTickets);
       }
    } 


OR
  1. class Test
  2. {
  3.    static void Main()
  4.    {
  5.       int availableTickets;
  6.       int? ticketOnSale = null;

  7.        availableTickets = ticketOnSale??0;      // null-coalescing operator              

  8.       Console.WriteLine(availableTickets);
       }
    } 

Wednesday, 10 December 2014

Number Pattern in C# - 15 (Pascal Triangle)

Ques: Write a program to print PASCAL triangle



In pascal triangle we start with print "1" at the top, and after that continue placing numbers below it in the for pyramid triangle. Each number in this triangle is the sum of above two number starting from left.

Suppose we have to print this pascal triangle
    
      1                        
      1  1                      
    1  2  1                     
  1  3  3  1           
1  4  6  4  1                

ROW 0 = 1;
ROW 1 = ( 0 + 1);
ROW 2 = ( 0 + 1)( 1 + 0);
ROW 3 = ( 0 + 1 )( 1 + 2 )( 2 + 1 )( 1 + 0 );
ROW 4 = ( 0 + 1 )( 1 + 3 )( 3 + 3 )( 3 + 1 )( 1 + 0 );


There are lots of way to create Pascal Triangle Two of them are here

Source Code 1:

  1. using System;  
  2. public class PascleTriangle  
  3. {  
  4.     public static void Main()  
  5.     {  
  6.         int row,i,j,c;  
  7.         Console.Write("Enter the no. of row you want to print: ");  
  8.         row=Convert.ToInt32(Console.ReadLine());  
  9.     
  10.         for(i=0;i<=row;i++)  
  11.         {  
  12.             c=1;  
  13.             for(j=i;  j<=row-1; j++)  
  14.             Console.Write(" ");  
  15.           
  16.             for(j=0;j<=i;j++)  
  17.             {  
  18.                 Console.Write("{0} ",c);  
  19.                 c=(c*(i-j)/(j+1));  
  20.             }  
  21.             Console.WriteLine();      
  22.         }  
  23.         Console.ReadLine();  
  24.     }  
  25. }

OR

Source Code 2:

  1. using System;  
  2. public class PascleTriangle  
  3. {  
  4.     public static void Main()  
  5.     {  
  6.         int i,j,row,pas;  
  7.           
  8.         Console.Write("Enter the no. of rows in pascle Triangle: ");  
  9.         row=Convert.ToInt32(Console.ReadLine());  
  10.   
  11.         for(i=0; i<=row;i++)  
  12.         {  
  13.             for(j=0;j<=(row-i);j++)  
  14.             Console.Write(" ");  
  15.   
  16.             for(j=0; j<=i; j++)  
  17.             {  
  18.                 pas=calc(i)/(calc(j)*calc(i-j));  
  19.                 Console.Write("{0} ",pas);  
  20.             }  
  21.             Console.WriteLine();  
  22.         }  
  23.         Console.ReadLine();  
  24.     }  
  25.   
  26.     public int calc(int num)  
  27.     {  
  28.         int x, res=1;  
  29.         for(x=1;x<=num;x++)  
  30.         res=res*x;  
  31.         return res;  
  32.     }  
  33. }  

  
Screen Shot of Pascal triangle
Fig: Screenshot of Output