Serving Information Simply

Saturday, 9 February 2013

Arrays in C#.net Programming.



This tutorial describes array programming in C# and .NET. It starts with the discussion of simple arrays and then proceeds into more complex topics such as jagged and multi-dimensional arrays.

Introduction

In C#, an array index starts at zero. That means the first item of an array starts at the 0th position. The position of the last item on an array will total number of items - 1. So if an array has 10 items, the last 10th item is at 9th position.

In C#, arrays can be declared as fixed length or dynamic.
fixed length array can store a predefined number of items.
dynamic array does not have a predefined size. The size of a dynamic array increases as you add new items to the array. You can declare an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined.
Let's take a look at simple declarations of arrays in C#. The below code defines the simplest dynamic array of integer types that does not have a fixed size.
int[] intArray;

The following code snippet declares an array that can store 5 items only starting from index 0 to 4.
int[] intArray;
intArray = new int[5];

Defining arrays of different types

In the previous code snippet, we saw how to define a simple array of integer type. Similarly, we can define arrays of any type such as double, character, and string.
In C#, arrays are objects. That means that declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator.
The following code snippet defines arrays of double, char, bool, and string data types.
double[] doubleArray = new double[5];
char[] charArray = new char[5];
bool[] boolArray = new bool[2];
string[] stringArray = new string[10];

Initializing Arrays

// Initialize a fixed array
int[] staticIntArray = new int[3] {1, 3, 5};

Alternative, we can also add array items one at a time as listed in the following code snippet.

// Initialize a fixed array one item at a time
int[] staticIntArray = new int[3];
staticIntArray[0] = 1;
staticIntArray[1] = 3;
staticIntArray[2] = 5;

The following code snippet declares a dynamic array with string values.

// Initialize a dynamic array items during declaration
string[] strArray = new string[] { "Abhinav Bajpai""Amiya bajpai""Raj Kumar""vikash Kumar""Sharad Kumar" };

Accessing Arrays

We can access an array item by passing the item index in the array.

// Initialize a fixed array one item at a time
int[] staticIntArray = new int[3];
staticIntArray[0] = 1;
staticIntArray[1] = 3;
staticIntArray[2] = 5;

// Read array items one by one
Console.WriteLine(staticIntArray[0]);
Console.WriteLine(staticIntArray[1]);
Console.WriteLine(staticIntArray[2]);

This method is useful when you know what item you want to access from an array. If you try to pass an item index greater than the items in array, you will get an error.

Accessing an array using a foreach Loop

The foreach control statement (loop) is used to iterate through the items of an array.

// Initialize a dynamic array items during declaration
string[] strArray = new string[] { "Abhinav Bajpai""Amiya bajpai""Raj Kumar""vikash Kumar""Sharad Kumar" };

// Read array items using foreach loop
foreach (string str in strArray)
{
    Console.WriteLine(str);
}

Note:-This approach is used when you do not know the exact index of an item in an array and needs to loop through all the items.

Types of array

*         Single-dimensional arrays
*         Multidimensional arrays or rectangular arrays
*         Jagged arrays
*         Mixed arrays.

Single Dimension Arrays

Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store number of items of a predefined type. All items in a single dimension array are stored contiguously starting from 0 to the size of the array -1.
Example-:
int[] intArray;
intArray = new int[3];

Array declarations in C# are pretty simple. You put array items in curly braces ({}). If an array is not initialized, its items are automatically initialized to the default initial value for the array type if the array is not initialized at the time it is declared.
int[] staticIntArray = new int[3] {1, 3, 5};

The following code declares and initializes an array of 5 string items.
string[] strArray = new string[5] { "Abhinav""vikash""Raj""Sharad""vimal" };

You can even directly assign these values without using the new operator.

string[] strArray = { "Abhinav""vikash""Raj""Sharad""vimal" };

You can initialize a dynamic length array as follows:

string[] strArray = new string[] { Abhinav""vikash""Raj""Sharad""vimal" };

Multi-Dimensional Arrays

A multi-dimensional array, also known as a rectangular array is an array with more than one dimension. The form of a multi-dimensional array is a matrix.

Declaring a multi-dimensional array

A multi dimension array is declared as following:
string[,] mutliDimStringArray;
A multi-dimensional array can be fixed-sized or dynamic sized.

Initializing multi-dimensional arrays

int[,] numbers = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[2, 2] { { " Abhinav "" Sharad " }, { " vikash "" Raj " } };

Now let's see examples of multi-dimensional dynamic arrays where you are not sure of the number of items of the array.

int[,] numbers = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[,] { { " Abhinav "" Sharad " }, { " vikash "" Raj " } };

You can also omit the new operator as we did in single dimension arrays. You can assign these values directly without using the new operator. For example:
int[,] numbers = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = { { " Abhinav "" Sharad " }, { " vikash "" Raj " } };

We can also initialize the array items one item at a time. The following code snippet is an example of initializing array items one at a time.

int[,] numbers = new int[3, 2];
numbers[0, 0] = 1;
numbers[1, 0] = 2;
numbers[2, 0] = 3;
numbers[0, 1] = 4;
numbers[1, 1] = 5;
numbers[2, 1] = 6;

Accessing multi-dimensional arrays

A multi-dimensional array items are represented in a matrix format and to access its items, we need to specify the matrix dimension. For example, item (1,2) represents an array item in the matrix at second row and third column.
The following code snippet shows how to access numbers array defined in the above code.
Console.WriteLine(numbers[0,0]);
Console.WriteLine(numbers[0, 1]);
Console.WriteLine(numbers[1, 0]);
Console.WriteLine(numbers[1, 1]);
Console.WriteLine(numbers[2, 0]);
Console.WriteLine(numbers[2, 2]);

Jagged Arrays

Jagged arrays are arrays of arrays. The elements of a jagged array are other arrays.

Declaring Jagged Arrays

Declaration of a jagged array involves two brackets. For example, the following code snippet declares a jagged array that has three items of an array.

int[][] intJaggedArray = new int[3][];

The following code snippet declares a jagged array that has two items of an array.

string[][] stringJaggedArray = new string[2][];

Initializing Jagged Arrays

// Initializing jagged arrays
intJaggedArray[0] = new int[2];
intJaggedArray[1] = new int[4];
intJaggedArray[2] = new int[6];

We can also initialize a jagged array's items by providing the values of the array's items. The following code snippet initializes item an array's items directly during the declaration.

// Initializing jagged arrays
intJaggedArray[0] = new int[2]{2, 12};
intJaggedArray[1] = new int[4]{4, 14, 24, 34};
intJaggedArray[2] = new int[6] {6, 16, 26, 36, 46, 56 };


Accessing Jagged Arrays

We can access a jagged array's items individually in the following way:

Console.Write(intJaggedArray3[0][0]);
Console.WriteLine(intJaggedArray3[2][5]);

We can also loop through all of the items of a jagged array. The Length property of an array helps a lot; it gives us the number of items in an array.

// Loop through all itesm of a jagged array
for (int i = 0; i < intJaggedArray3.Length; i++)
{
    System.Console.Write("Element({0}): ", i);
    for (int j = 0; j < intJaggedArray3[i].Length; j++)
    {
        System.Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length - 1) ? "" : " ");
    }
    System.Console.WriteLine();
}

Mixed Arrays

Mixed arrays are a combination of multi-dimension arrays and jagged arrays. The mixed arrays type is removed from .NET 4.0. I have not really seen any use of mixed arrays. You can do anything you want with the help of multi-dimensional and jagged arrays.

A Simple Example
  
Console.WriteLine("Single Dimension Array Sample");
// Single dim array
string[] strArray = new string[] { "Abhinav Bajpai""raju Verma""Viaksh dwevedi""Sharad Mishra""Vimal tripathi" };
// Read array items using foreach loop
foreach (string str in strArray)
{
    Console.WriteLine(str);
}
Console.WriteLine("-----------------------------");

Console.WriteLine("Multi-Dimension Array Sample");
string[,] string2DArray = new string[2, 2] { { "abhi""raj" }, { "Amiya""shreya" } };
foreach (string str in string2DArray)
{
    Console.WriteLine(str);
}
Console.WriteLine("-----------------------------");

Console.WriteLine("Jagged Array Sample");
int[][] intJaggedArray3 =
{
    new int[] {2,12},
    new int[] {14, 14, 24, 34},
    new int[] {6, 16, 26, 36, 46, 56}
};
// Loop through all itesm of a jagged array
for (int i = 0; i < intJaggedArray3.Length; i++)
{
    Console.Write("Element({0}): ", i);
    for (int j = 0; j < intJaggedArray3[i].Length; j++)
    {
        Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length - 1) ?"" : " ");
    }
    Console.WriteLine();
}
Console.WriteLine("-----------------------------");


Thanks Guys ....keep visiting..:)

2 comments: