Showing posts with label Basic Concepts. Show all posts
Showing posts with label Basic Concepts. Show all posts

Tuesday, 27 January 2015

Arrays using Command - Line Arguments

Introduction :

In many system it is possible to pass argument from the command line (known as command line argument) to an application by including a parameter of type string[] (i.e. an array of string) in the parameter list of Main. We named this parameter args. When an application is executed from the the command prompt, the execution environment the command-line argument that appear after the application name the application's main method as string in the one dimensional array args. The Number of argument passed from the command line is obtained from the accessing the arrays length property. For example the command  "MyApplication a b"  passes two command line argument to application MyApplication. Note that command line argument separated by white space not commas.

Example

  1. using System;  
  2. public class InitArray  
  3. {  
  4.     public static void Main(string[] args)  
  5.     {  
  6.         if(args.Length != 3)  
  7.             Console.WriteLine("Please re-enter the entire command including\n An array size, Initial Value and Increament");  
  8.   
  9.         else  
  10.         {  
  11.             int arrayLength = Convert.ToInt32( args[0] );  
  12.             int[] array = new int[ arrayLength ];  
  13.   
  14.             int initialValue = Convert.ToInt32( args[1] );  
  15.             int increament = Convert.ToInt32( args[2] );  
  16.   
  17.             forint counter = 0; counter<array.Length; counter++ )  
  18.                 array[counter] = initialValue + increament * counter;  
  19.   
  20.             Console.WriteLine( "{0}{1,8}""Index""Value" );  
  21.   
  22.             for(int counter = 0; counter < array.Length; counter++)  
  23.   
  24.             Console.WriteLine("{0,3}{1,8}", counter, array[counter]);  
  25.         }  
  26.     }  
  27. }  


In the above example it takes three command line arguments to initialize the array. First is the length of the array Second is the initial value of the array third is the Increment between values in the array.


Output of Command line argument
Fig: Screenshot of output


In this Output the size of array is 5 the initial value of array is 0 and there is increment of 8.



Variable-Length Argument Lists (VARARGS)

Introduction:

Variable - length argument lists allow you to create methods that receive an arbitrary number of arguments. A one-dimensional array-type argument preceded by the keyword params in a method's parameter list indicates that the method receives a variable number of argument with the type of array elements. This use of params modifiers can occurs only in the last entry of the parameter list. While you can use method overloading and arraypassing to accomplish much of what is accomplished with "varargs"- another name for variable length argument lists-using the param modifiers is more concise.

Example:

  1. using System;  
  2. public class VarargsTest  
  3. {  
  4.     public static double Average(params double[] numbers)  
  5.     {  
  6.         double total = 0.0;  
  7.         foreach(double d in numbers)  
  8.             total += d;  
  9.   
  10.         return total/numbers.Length;  
  11.     }  
  12.   
  13.     public static void Main()  
  14.     {  
  15.         double d1 = 10.0;  
  16.         double d2 = 12.5;  
  17.         double d3 = 15.6;  
  18.         double d4 = 14.8;  
  19.   
  20.         Console.WriteLine( "d1 = {0:F2}\nd2 = {1:F2}\nd3 = {2:F2}\nd4 = {3:F2}", d1, d2, d3, d4 );  
  21.   
  22.         Console.WriteLine("Average of d1 and d2 is {0:F2}", Average(d1, d2));  
  23.         Console.WriteLine("Average of d1, d2 and d3 is {0:F2}", Average(d1, d2, d3));  
  24.         Console.WriteLine("Average of d1, d2, d3 and d4 is {0:F2}", Average(d1, d2, d3, d4));  
  25.   
  26.         Console.ReadLine();  
  27.     }  
  28. }  


Output of varargs
Fig: Screenshot of Output




Monday, 26 January 2015

Arrays in C-sharp

Contents:


  • Introduction
  • Syntax
  • Defining Array
  • Initializing Array
  • Accessing Array
  • Types of Array
  • Array Class
  • Array Properties
  • Array class Methods
  • Getting and Setting value in array



Introduction :


  • An Array is the collection of similar data type.
  • An array is a special variable which is use to perform operation more than one value of same type at a time.
  • An array starts at zero means the first item of an array is at 0th position.
  • Position of last item of an array will be total no. of item -1.
  • Array can be declared as fixed length and dynamic.
  • Array cannot grow in size once initialized have to rely on integral indices to store or retrieve items from the array.


Syntax :

           int[] arr ;
           arr = new int[5];

or

          int[] arr = new int[5];


Defining Arrays of different types :

double[] douarr = new double[10];
char[] chararr = new char[10];
bool[] boolarr = newbool[2];
string[] strarr = new string[6];

Initializing Arrays :

Initializing a fixed array
                       int[] staticarr = new int[3] {1,3,5}

Initializing a fixed array one item at a time
                      staticarr[0]  = 1;
                      staticarr[1]  = 1;
                      staticarr[2]  = 1;

Initializing a dynamic Array
                     string[] arr = new string[] {"John","Samson","Michael"};

Accessing Array :

Initializing fixed Array one at a time

                     Int[] staticarr = new Int[3];
                             staticarr[0] = 1;
                             staticarr[1] = 2;
                             staticarr[3] = 3;

 Read Array item one by one

                     Console.WriteLine(staticarr[0]);
                     Console.WriteLine(staticarr[1]);
                     Console.WriteLine(staticarr[2]);

Accessing an array using foreach loop

                     int[] arr = new int[]{1,2,3,4,5};
                     foreach(int i in arr)
                     {
                             Console.WriteLine(i);
                      }

Types of Array :

*Single-dimensional Array
*Multi-Dimensional Array
*Jagged Array


Single dimensional Arrays

int[] Array = new int[3]{1,3,5};
int[] Array = {1,3,5,7};
int[] Array = new int{1,3,5};

Multi dimensional Arrays :  Array with more than one dimensions

string[,] multiDstring = new string[2,2]{{"john", "Samson"},{"Hardik","ramson"}};

int[,] multiDint = new int[2,2] {{1,2},{5,8}};
int[,] multiDint = {{1,5},{2,4},{3,4}};

int[,] number = new int[2,2];
number[0,0] = 1;
number[0,1] = 8;
number[1,0] = 9;
number[1,1] = 15;

Accessing multi-dimensional arrays

Console.WriteLine(number[0,0]);
Console.WriteLine(number[0,1]);
Console.WriteLine(number[1,0]);
Console.WriteLine(number[1,1]);

Jagged Arrays

*Array of arrays
*Element of jagged arrays are the other arrays.

Declaration of jagged Arrays

int[][] intJArr = new int[3][];
string[][] sJArr = new string[2][];

int JArr[0] = new int[2] {2,14};
int JArr[1] = new int[4] {2,6,16,14};
int JArr[2] = new int[3] {2,1,87};

Accessing jagged Array  : we can access a jagged item

Console.Write(JArr[0][0]);
Console.WriteLine(JArr[1][3]);

Accessing of jagged array using Loop :

for(int i = 0; i <JArrLength; i++)
{
      Console.Write("Element [{0}] : ", i)
       for(int j = 0; j <JArr; j++)
       {
                Console.Write("{0}{1}", JArr[i][j], j == (JArr[i].Length - 1) ? "" : " " ); //**
        }
}

**this is conditional statement in which  JArr[i].Length – 1 getting an array length-1 if its try it print nothing also its false it will print nothing.
This is what this line is doing.

Note:-The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.

condition ? first_expression : second_expression;

However, the high-level ternary statement is useful because it allows you to condense multiple if-statements and reduce nesting. It does not actually eliminate branching. It simplifies the high-level representation of the branching.

Example:

C# program that uses ternary operator
 
using System;
 
class Program
{
    static void Main()
    {
        //
        // If the expression is true, set value to 1.
        // Otherwise, set value to -1.
        //
        int value = 100.ToString() == "100" ? 1 : -1;
 
        Console.WriteLine(value);
    }
}
 
Output : 1


Array Class :

Mother of all array and provide functionality for creating, manipulating, searching and sorting arrays. Array class, defined in the system namespace, is the base class for array in c-sharp. Array class is the abstract base class that means we cannot create the instance of array class.

Creating an Array :

        Array class provide the CreateInstance method to construct an array. The CreateInstance method take first parameter as the type of item and second and third are the dimensions of there range.

Once array is created we use SetValue to add and modify item of an array.

Array SArray = CreateInstance(typeof(String),3);
SArray.SetValue = ("Ravi rampal",0);   //old value
SArray.SetValue = ("Johny Kennedy",1);
SArray.SetValue = ("Sachin tendulkar",0);    // modified value 
SArray.SetValue = ("Nick floyed",2);

Note: - always print modified value in the above statements Sachin Tendulkar is print in console instead of  Ravi rampal.

Array properties :


  • IsFixedSize : Return a value indicating if an array has fixed size or not.
  • IsReadOnly : Return a value if an array read only or not.
  • LongLength: Return 64 bit integer represent total items in array.
  • Length: Return 32 bit integer represent total items in array.
  • Rank: Return no. of dimensions of an array.
  • SyncRoot: Return an object that can be used to synchcronize access  to the array.




Array Class Method :


  • BinarySearch: This method searches one-dimensions sorted array for a value, using a binary search algorithm.
  • Clear: This method removes all the items of an array and set a range of items in the array to 0.
  • Copy: This Method copy a section of one array to another array and perform typecasting and boxing as required.
  • CopyTo: Copies all the item of current one-dimensional array to the specified one-dimensional array starting at the specified destination index.
  • CreateInstance: Initialize a new instance of an array class or construct a new array.
  • GetEnumerator: Returns a IEnumerators for the array.
  • GetLength: Returns the no. of items in an array.
  • GetLowerBound: Returns a Lower Bound of an array.
  • GetUpperBound: Returns Upper Bounds Of an array.
  • GetValue: Returns the value of specified Items in an array.
  • IndexOf: This method returns the first occurrence of a value in one-dimensional array or in a portion of the array.
  • Initialize: Initialize every item of the value type array by calling the default constructor of the value type.
  • LastIndexOf: Return the index of last occurrence of a value in array or in a portion of the array.
  • Reverse: This method reverse the order of items in the one-dimensional array or in a portion of array.
  • SetValue: This method set the specified items in the current array to the specified value.
  • Sort: Sort the items in the one-dimensional array.


Getting and setting value in array :

GetValue returns a value from index of an array items at a specific index.

Setvalue set and modified value of an array items at a specified index.

Array names = Array.CreateInstance(typedef(string) 2,2)

names.SetValue("Rosy",0,0);
names.SetValue("Amy",0,1);
names.SetValue("Peter",1,0);
names.SetValue("John",1,1);



Monday, 12 January 2015

Method in C-sharp

Advantage:

1.Method also known as function. these terms use interchangeably.
2.In method you define your logic at once and use it at many places.
3.It makes maintenance of your application easy.

Syntax:

[attributes] access-modifiers return-type method-name(Parameter)
{
      method body;
}

a. Return type can be any data type or void.
b. Method name can be a meaningful name.
c. Parameters are optional.

Static and Instance methods

a. When a method declaration includes a static modifiers, that method is said to be static method.

b.Static method is invoked using class name, where as an instance method is invoked  using instance of the class.

  1. class Demo  
  2. public static void Main()           //main method  
  3. {  
  4.     Demo.Add();                        //static method call  
  5.     Demo d = new Demo();  
  6.     d.sub();                                   // instance method call  
  7. }  
  8.   
  9. public static void Add()                  //Static method  
  10. {  
  11.     
  12. }  
  13.   
  14. public void Sub()                       //Instance method  
  15. {  
  16.   



c. Multiple Instances of class is created (or instantiated) and each instance has its own separate method. However when a method is static, there are no instance of the method, and you can invoke only the one definition of static method.





Types of Method

1.Pass by value/value parameter
2.pass by reference/reference parameter
3.Parameter array
4.Out Parameter



1.Pass by Value/Value Parameter



I and J are pointing to different memory location operation one variable not affect the value of other variable.






Example:

  1. class Demo  
  2. {  
  3.    public static void Main()  
  4.    {  
  5.        int i = 0;  
  6.        Simplemethod(i);  
  7.       Console.WriteLine(i);  
  8.    }  
  9.   
  10.   public static void Simplemethod(int j)  
  11.  {  
  12.       j=101;  
  13.  }  
  14. }

Output: 0


Henceforth, Pass by value parameter is creates a copy of the parameter passed, so modification does not affect each other.



2.Pass by reference/Reference Parameter

I and J pointing to the same memory location.  Operation on one variable will directly affect the  value of other variable.






Example:

  1. class Demo    
  2. {    
  3.    public static void Main()    
  4.    {    
  5.        int i = 0;    
  6.        Simplemethod(ref i);    
  7.       Console.WriteLine(i);    
  8.    }    
  9.     
  10.   public static void Simplemethod(ref int j)    
  11.  {    
  12.       j=101;    
  13.  }    

Output: 101


The ref method parameter keyword on a method parameter causes a method to refers to the same variable that was passed into the method. Any change made to the parameter in the method will be reflected in that variable when control passes back to the calling method.



3.Out Parameter:

               Use when you want a method returns more than one value.

Example:

  1. class Demo  
  2. {  
  3.    public static void Main()  
  4.    {  
  5.         int total=0;  
  6.         int product = 0;  
  7.       
  8.        calculate(10,20,out total,out product);  
  9.   
  10.        Console.WriteLine("Sum = {0} && Product = {1}", total, product);  
  11.    }  
  12.   
  13.   public static void Calculated(int FN, int SN, out int Sum, out int Product)  
  14.   {  
  15.        Sum=SN+FN;  
  16.        Product = SN*FN;  
  17.   }  
  18. }  

Screenshot of output
Fig:Output of out Parameter

   


4.Parameter Arrays:

             The PARAMS KEYWORD LETS YOU SPECIFY A METHOD THAT TAKES A VARIABLE NUMBER ARGUMENTS. YOU CAN SEND A COMMA SEPARATED LIST OF ARGUMENTS  OR AN ARRAY OR NO ARGUMENT.
            Params keyword should be last one in a method declaration and only one params keyword is permitted in a method declaration.

Example:

  1. class System;  
  2. {  
  3.    public static void Main()  
  4.    {  
  5.        int[] Numbers = new int[3];  
  6.               
  7.          Number[0]=101;  
  8.          Number[1]=102;  
  9.          Number[2]=103;  
  10.   
  11.        // ParamsMethod();  
  12.         ParamsMethod(Numbers);  
  13.        // ParamsMethod(1,2,3,4,5);  
  14.    }  
  15.   
  16.   public static void ParamsMethod(params int[] Numbers)   // method Parameter
  17.   {  
  18.      Console.WriteLine("There are {0} Elements ", Numbers.Length);  
  19.   
  20.      foreach(int i in Numbers)  
  21.      {  
  22.           Console.WriteLine(i);  
  23.      }  
  24.   }  
  25. }  

Screenshot of output
Fig: Output of Params Method