Arrays in C# - C# FOR BEGINNERS CRASH COURSE (2014)

C# FOR BEGINNERS CRASH COURSE (2014)

Chapter 9 Arrays in C#

9.1 Introduction to arrays

An array is a collection of values of similar data type. The variables in the array are known as the elements of the array. The array elements are accessed using a single name and an index number representing the position of the element within the array.

An array has a rank that determines the number of indices associated with every array element. The rank of the array is also referred to as the dimensions of the array. The following figure shows the array structure in the system.

9.2 Arrays declaration

An array is declared before it is used in any program. The following syntax is used to declare an array.

datatype[ ] ArrayName;

The syntax of an array involves the components mentioned below:

· datatype: Used for specifying the data type for elements. It will be stored in an array.

· [ ] : Specify the size of the array and is referred to as rank.

· ArrayName: States the name of the array.

9.3 Initializing and adding values

The new keyword is used to create an instance of the array. The size of array is specified when it is initialized. The following code snippet is used to initialize the array.

int [ ] x ;

x = new int [15];

The array can be initialized by combining the two statements and is written as:

int [ ] x = new int [15];

Assigning values to an array

The values can be assigned to each element of the array using the index number. It is also known as subscript of the element. The following code snippet is used for assigning the values to an array.

int [ ] amount = new int [5];

int [0] = 50;

The array can be created and initialized using the following code:

int [ ] amount = { 40,60,70,80};

The size of an array can be removed.

int [ ] age = new int[ ] { 21,31,40};

When a user copies the data from one array into another, the source and target array refer to same location. The following code snippet shows the copying of one array to another.

int [ ] age = new int[ ] { 12,14,15,16};

int [ ] amount = age;

The two arrays as age and amount are created. They point to same memory location.

9.4 Accessing array elements

To access an element in an array, you will need to use an index. An index is the number that represents the position of elements in the array. Indexes always start from zero, so to access the first element in an array we would do so in this format:

array_name[index]

In this case the value of index will be zero.

Example:

Example 28:

using System;

namespace arraydeclare

{

class Arraydemo

{

static void Main(string[] args)

{

int [] a = new int[5];

int x,y;

for(int x = 0;x <5;x++)

{

a[x]=x + 10;

}

for(y = 0;y < 5;y++)

{

Console.WriteLine("Element [{0}]={1}",y,a[y]);

}

Console.ReadLine();

}

}

}

When the code is compiled and executed, the output is:

Element [0] = 10

Element [1] = 11

Element [2] = 12

Element [3] = 13

Element [4] = 14

9.5 Foreach loop

This loop is specifically designed to iterate through all elements of an array. It is great for retrieving elements of an array efficiently.

Syntax:

foreach(type identifier in expression)

statement – block

Example:

Example 29:

using System;

namespace arraydeclare

{

class Arraydemo

{

static void Main(string[] args)

{

int [] a = new int[5];

for(int x = 0;x < 5;x++)

{

a[x] = x + 10;

}

foreach(int y in a)

{

int x = y - 10;

Console.WriteLine("Element[{0}]",x,y);

x++;

}

Console.ReadLine();

}

}

}

The code is compiled and executed, the output is:

Element [0] = 10

Element [1] = 11

Element [2] = 12

Element [3] = 13

Element [4] = 14

9.6 Different C# arrays

The following are various types of C# arrays that are used for developing code.

Multi-dimensional arrays

A multi-dimensional array stores data in more than one row dimension. It is also known as rectangular array. User can declare two-dimensional array of integer as:

int [ , ] no;

A two-dimensional array can be considered as table. It has x rows and y columns. A two-dimensional array contains 2 rows and 4 columns.

Initializing two dimensional arrays

The following array has 3 rows and 3 columns.

int [ , ] x = int [ 3, 3] = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

Accessing elements of multidimensional array

An element from the multi dimensional array can be accessed using the subscripts. They are row and column index of the array.

Example:

int output = a [1, 2];

In the above statement, the element from second row and third column is accessed.

Example:

Example 30:

using System;

namespace twodimension

{

class multiarray

{

static void Main(string[] args)

{

int [ , ] x = new int[3,2]{{1,1},{2,2},{3,3}};

int a,b;

for(a = 0;a < 3;a++)

{

for(b = 0;b < 2;b++)

{

Console.WriteLine("x[{0},{1}={2}",a,b,x[a,b]);

}

}

Console.ReadLine();

}

}

}

The code is compiled and executed, the output is:

x[0,0] = 1

x[0,1] = 1

x[1,0] = 2

x[1,1] = 2

x[2,0] = 3

x[2,1] = 3

Jagged Array

A jagged array is an array of arrays. The jagged array of int type is declared as:

int [ ] [ ] marks;

An array can be initialized as:

int [ ] [ ] marks = new int [3] [ ] { new int [ ] {45,57,78}, new int [ ] { 60, 75, 86,45,35}};

The marks array is of two arrays of integers as marks[0] with 3 integers and marks[1] with 5 integers.

Example:

Example 31:

using System;

namespace Jaggedarray

{

class jagged

{

static void Main(string[] args)

{

int[][] x = new int[][]{

new int[]{0,0},

new int[]{2,2},

new int[]{3,4},

new int[]{4,2},

new int[]{1,3}};

int a,b;

for(a = 0;a < 5;a++)

{

for(b = 0;b < 2;b++)

{

Console.WriteLine("x[{0},{1}]={2}",a,b,x[a][b]);

}

}

Console.ReadLine();

}

}

}

The code is compiled and executed, the output is:

x[0,0] = 0

x[0,1] = 0

x[1,0] = 2

x[1,1] = 2

x[2,0] = 3

x[2,1] = 4

x[3,0] = 4

x[3,1] = 2

x[4,0] = 1

x[4,1] = 3

Param Arrays

When a method is declared, the number of arguments to be passed as parameter is not decided. The Param array is used.

Example:

Example 32:

using System;

namespace ParamArray

{

class ParamArray

{

public int AddValues(params int[] data)

{

int total = 0;

foreach(int a in data)

{

total+ = a;

}

return total;

}

}

class Test

{

static void Main(string[] args)

{

ParamArray pa = new ParamArray();

int total=pa.AddValues(2,3,4,5,6);

Console.WriteLine("The sum is {0}",total);

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

The sum is 20

Array Class

The array class is the base class for all arrays in C#. The System namespace contains the array class. There are various properties and methods used in the array class.

Properties of Array class

· Length: The total number of items in all dimensions of an array are returned

· Rank: It returns the rank of an array

· IsFixedSize: It is a value indicating an array has fixed size or not

· IsReadOnly: Value stating the array is read only or not

Methods of Array class

· Sort: The sort operation on an array passed to it as a parameter

· Clear: It removes all the items in an array and sets range of items to 0

· GetLength: The number of items in an array are returned

· GetValue: The value of the specified item in an array

· IndexOf: The index of the first occurrence of a value in one dimensional array is returned

· Reverse: It reverses the sequence of elements in the array

Example:

Example 33:

using System;

namespace Array

{

class Array1

{

static void Main(string[] args)

{

int[] item = {12,34,23,55,64};

int[] value = item;

Console.Write(“Original Array:”);

foreach(int x in item)

{

Console.Write(x+" ");

}

Console.WriteLine();

//reverse the array

Array.Reverse(value);

Console.Write("Array reversed:");

foreach(int x in value)

{

Console.Write(x+" ");

}

Console.WriteLine();

//sort the array

Array.Sort(item);

Console.Write("Array sorted:");

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

Original Array: 12 34 23 55 64

Array reversed: 64 55 23 34 12

Array sorted: 12 23 34 55 64