Thursday, February 27, 2014

Array

Arrays

  • An array is the collection of similar type of values.
  • Each value in the array is to be called as an element.
  • The total no. of array elements is called as ―Array size‖.
Implementation of Arrays:

1. Single Dimensional Arrays:
  • Array declaration:
             Without initialization:
                datatype[]  arrayname = new  datatype[size];
             With initialization:
               datatype[]  arrayname = {val1,val2,val3,…..};

  • Accessing the elements:
              arrayname[index]

2. Double Dimensional Arrays:
  • Array declaration:
           Without initialization:
              datatype[,]  arrayname = new  datatype[rows size,columns size];
           With initialization:
              datatype[,]  arrayname = {{val1,val2,…}, {val1,val2,…},…};
  • Accessing the elements:
             arrayname[row index,column index
3.  Multi Dimensional Arrays:
           Same  as  ―Double‖  dimensional  arrays,  but  increase  the  no.  of dimensions


Download above code of Demo of Single Dim Array : Download Links



for loop program in c#


Download above code of Demo of Multiple Dim Array : Download Links


foreach Loop

  • One of the most common usages of the ―for‖ loop is to iterate through a collection of values (array).
  • C# offers a simplified and easier syntax of for loop called ―foreach loop‖, designed only for such kind of array iterations.
  • Syntax:
           foreach (datatype variable in arrayname)
           {     ;
                 ;
            }
  • In  the  above  syntax,  the  loop  will  be  executed  once  for  each  value  in  the  array.  For every iteration, the values of the array will be assigned to the variable.
  • For example, you take the following for loop.
             int[] nums = { 10, 20, 30};
             for (int i = 0;i < nums.Length; i++)
             {
               Console.WriteLine(nums[i]));
             }
  • You can re-write the above example with ―foreach‖ syntax as follows:
            int[] nums = { 10, 20, 30};
            foreach (int n in nums)
             {
               Console.WriteLine(n);
             }
Note: The arrayname.Length‖ property gets the size of the array. We discuss about the "Array"
           class in future.

Jagged Arrays

  • A two-dimensional array is of rectangular size always.
  • But the jagged arrays are more flexible in sizing them.
  • They may not be rectangular size.
  • To  declare  them,  declare  the  array  size  in  one  brackets  [size]  and  then  give  empty brackets, because different no. of elements can be stored in each row
jagged array

array

Download of Demo on Jagged Arrays  :  Download Links