Friday, September 30, 2011

2D array


2D Array
Assigning values to 2D array while Declaration –
int[,]arr = { {11,12,13,14},
{21,22,23,24},
{31,32,33,34},
};
Jagged ArraysThese are also two dimensional that contains rows and columns whereas in two dimensional arrays all the rows will have same no of columns but in a jagged array each row will be having varying or different no of columns.

This are also referred as array of arrays because multiple single dimensional array are combined together to form a new array.
(type)[ ][ ] (name) = new (types)[rows][ ];
int[ ][ ] arr = new int[5][ ];
int [ ] arr = {list of values};
To declare a jagged array in the initial declaration we can only specified the no of rows to the array but not the columns because columns are not fixed.
int[ ][ ] arr = new int[4][ ];
After specifying the no of rows now pointing to each row we need to specify the no. of columns to the row.
int [ ] [ ] arr = new int[4][ ];
arr[0] = new int[5];
arr[1] = new int[6];
arr[2] = new int[8];
arr[3] = new int[4];

        Program
For Assigning Values to Jagged Array while Declaration –
int [ ][ ]arr = {
new int[3]{11,12,13},
new int[5]{21,22,23},
new int[4]{31,32,33},
new int[3]{41,42}
};
Command Line Parameters In the execution of a program it may required from values that needs to supplied in rum time where the values can be supplied in two diff ways –
  1. The program prompts for a value for which we supply the value and within the program the value is captured using reed line method.
  2. In the second case you can supply a list of values for any program at the of execution from the command prompt besides the program name, separating each value with a space.
    using System;
    class ParamsDemo
    {
    static void Main(string[] args)
    {
    foreach(string str in args)
    Console.WriteLine(str);
    }
    }
    For the above program while executing the program we can supply a list of values as command line parameters where all those values will be tacking into the string array of main method. To check the execute the above program as following.
    C:\csharp4>ParamsDemo 100 hello 3.14 true
    Program –
using System;
class AddParams
{
static void Main(string[] args)
{
int sum = 0;
foreach(string str in args)
sum += int.Parse(str);
Console.WriteLine(sum);
}
}

No comments: