Objective of the Module
- Introduction
- Arrays Overview
- Declaration of Arrays
- Reference Type
- Array Exception Handling
- Multi-Dimension Arrays
Introduction
Arrays are powerful data structures for solving many programming problems. You saw during the creation of variables of many types that they have one thing in common, they hold information about a single item, for instance an integer, float and string type and so on. So what is the solution if you need to manipulate sets of items? One solution would be to create a variable for each item in the set but again this leads to a different problem. How many variables do you need?
So in this situation Arrays provide mechanisms that solves problem posed by these questions. An array is a collection of related items, either value or reference type. In C# arrays are immutable such that the number of dimensions and size of the array are fixed.
Arrays Overview
An array contains zero or more items called elements. An array is an unordered sequence of elements. All the elements in an array areof the same type (unlike fields in a class that can be of different types). The elements of an array accessed using an integer index that always starts from zero. C# supports single-dimensional (vectors), multidimensional and jagged arrays.
Elements are identified by indexes relative to the beginning of the arrays. An index is also commonly called indices or subscripts and are placed inside the indexing operator ([]). Access to array elements is by their index value that ranges from 0 to (length-1).
Array Properties
- The length cannot be changed once created.
- Elements are initialized to default values.
- Arrays are reference types and are instances of System.Array.
- Their number of dimensions or ranks can be determined by the Rank property.
- An array length can be determined by the GetLength() method or Length property.
Simple Arrays Example
In the following example, at line 10 we are declaring an Integer type array variable myArrays with length 5. Which means the myArrays variable can hold 5 integer elements. From line 15, we are accessing each element using a for loop and doing an even number of calculations over them. Finally at line 21, we are displaying each element.
- using System;
-
- namespace Arrays
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- int[] myArrays = new int[5];
-
- Console.WriteLine("Simple Array Example");
-
-
- for (int i = 0; i < myArrays.Length; i++)
- {
-
- myArrays[i] = i * 2;
-
-
- Console.WriteLine(myArrays[i]);
- }
-
- Console.ReadKey();
- }
- }
- }
Once we compile this program it displays 5 even numbers on the screen. Because we have configured the arrays variable to hold up to 5 elements only as in the following.
Figure 1.1- Simple array output
Declaration Arrays
An array is a contiguous memory allocation of same-sized data type elements. After declaring an array, memory must be allocated to hold all the elements of the array. An array is a reference type, so memory on the heap must be allocated.
Figure 1.2- Array Declaration
The preceding figure shows the array declaration and allocation syntax for a single-dimension array having a specific type and length. The declaration begins with the array element type. The element of an array can be a value type or reference type. The element is followed by a set of empty brackets. Single-dimension arrays use one set of brackets. The element type, plus the brackets, yields an array type. This array type is followed by an identifier that declares the name of the array.
To actually allocate memory for an array, use the new operator followed by the type of elements the array can contain followed by the length of the array in brackets.
For example, the following line of code declares and allocates memory for a single-dimension array of integer having a length of 3.
- int[] myArrays = new int[3];
The following line of code would simply declare an array of floats:
And this code would allocate memory (initialize) to hold 6 float values:
The following line of code would simply declare an array of strings:
- String[] arry = new String[8];
You can also assign values to every array element using an array initialize.
- int[] arry = new int[5] { 15, 3, 7, 8, 9 };
Example-Finding an Array type, Rank and Total elements;
The following example calculates an integer type array length, type and rank (dimension).
- using System;
-
- namespace Arrays
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- int[] arry = new int[5];
-
- Console.WriteLine("Type=" + arry.GetType());
- Console.WriteLine("Rank=" + arry.Rank);
- Console.WriteLine("Length=" + arry.Length);
-
- Console.ReadKey();
- }
- }
- }
Vector Array using Literal Values
Up to this point you have seen how memory for an array can be allocated using the new operator. Another way to allocate memory for an array and initialize its elements at the same time is to specify the contents of an array using array literal values.
- int[] arry = {1,2,3,4,5};
The length of an array is determined by the number of literal values appearing in the declaration.
- string[] arry = {"A", "J", "A", "Y"};
-
- bool[] arry = {true, false};
Example-Concatenation of Two Strings
The following example shows the concatenation of two words.
- using System;
-
- namespace Arrays
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- string[] arry = {"Barack" , "Obama"};
-
-
- Console.WriteLine(arry[0] + " " + arry[1] );
-
- Console.ReadKey();
- }
- }
- }
Example-Finding Largest Number in Range of Integers
The following first declares an integer type of array with length of 5 then it iterates through with all the elements to determine the largest number in the array via for loop. Meanwhile, it also checks all the values with the variable x. If the value of x is greater than each element then one by one it continues the loop, otherwise it changes the value of x by assigning the current element value. Finally it prints the largest values.
- using System;
-
- namespace Arrays
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- int[] arry = {5,3,7,8,9};
-
- int x=0;
-
- for (int i = 0; i < arry.Length; i++)
- {
-
- if (x > arry[i])
- {
- continue;
- }
- else
- {
- x = arry[i];
- }
- }
-
- Console.WriteLine("Largest Number=" + x);
-
- Console.ReadKey();
- }
- }
- }
Reference Type
A Reference Type of an array can be implemented by creating a custom class. A variable of a reference type does not contain its data directly. However, you cannot change the value of the reference itself. Let's start with a Customer class with two constructors, the properties FirstName and LastName and an override of the ToString() method for concatenation of the two words. In the main class we create an array of Customer class objects with length 2 and finally print the FirstName and LastName via iterating the foreach loop as in the following:
- using System;
-
- namespace Arrays
- {
- public class Customer
- {
- public Customer() { }
-
- public Customer(string fname,string lname)
- {
- this.fname = fname;
- this.lname = lname;
- }
- private string fname;
- private string lname;
-
- public string FirstName
- {
- get { return fname; }
- set { fname = value; }
- }
-
- public string LastName
- {
- get { return lname; }
- set { lname = value; }
- }
- public override string ToString()
- {
- return fname + " " + lname;
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Customer[] obj = new Customer[2];
- obj[0] = new Customer("ajay","yadav");
- obj[1] = new Customer("tom","hanks");
-
- foreach(Customer i in obj)
- {
- Console.WriteLine(i.ToString());
- }
- Console.ReadKey();
- }
- }
- }
Array Exception Handling
Sometimes we unintentionally create glitches in the code pertaining to an array index range. For example in the following program we are calculating the sum of five numbers. So at line 5, in the for loop we are putting an equal sign in the condition. In that case the loop will execute 6 times rather than 5 times; this eventually generates an Index out of range error.
However due to evading such coding glitches we are putting the significant code into the try block and using a catch block we are flashing an alert message for index out of range as in the following:
Multi-Dimension Arrays
Ordinary arrays are indexed by a single integer. A multidimensional array is indexed by two or more integers. Declaring a 2-dimensional array with C# is done by putting a semicolon inside the brackets. The array is initialized by specifying the size of every dimension. Then the array elements can be accessed using two integers with the indexer.
Here we are declaring a 2D array that has two rows and two columns and assigning them values:
-
- int[,] dArray = new int[2,2];
- dArray[0, 0] = 1;
- dArray[0, 1] = 2;
- dArray[1, 0] = 3;
- dArray[1, 1] = 4;
A 2D array can be visualized as a grid or matrix comprised of rows and columns. The following table depicts a 2 X 2 dimension array with values in the corresponding rows and columns as in the following.
You can also initialize the 2D array using an array indexer if you know the value for the elements in advance as in the following:
-
- int[,] dArray ={
- {1,2,3},
- {4,5,6}
- };
The following program generates a double-dimension array grid by providing the values as well as it calculate the total number of elements with ranks:
- using System;
-
- namespace Arrays
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Enter the Rank::");
- int row = Int32.Parse(Console.ReadLine());
- int cols = Int32.Parse(Console.ReadLine());
- Console.WriteLine("__________________________");
- int[,] doubleArray = new int[row, cols];
-
- for (int i = 0, j = 1; i < doubleArray.GetLength(0); i++)
- {
- for (int k = 0; k < doubleArray.GetLength(1); k++)
- {
- doubleArray[i, k] = j++;
- Console.Write("{0:D3} ", doubleArray[i, k]);
- }
- Console.WriteLine();
- }
-
- Console.WriteLine();
- Console.WriteLine("Rank=" + doubleArray.Rank);
- Console.WriteLine("Elements=" + doubleArray.Length);
-
- Console.ReadKey();
- }
- }
- }
When you compile this program, it asks you to enter the dimension (rank) of the array and then it displays the values in the form of a matrix as in the following:
Figure 1.3- 2D Array
Rectangular arrays can be initialized using the literal values in an array initialization expression as in the following.
- using System;
-
- namespace Arrays
- {
- class Program
- {
- static void Main(string[] args)
- {
- char[,] doubleArray = {
- {'A','B','C'},
- {'D','E','F'},
- {'G','H','I'}
- };
-
- for (int i = 0; i < doubleArray.GetLength(0); i++)
- {
- for (int k = 0; k < doubleArray.GetLength(1); k++)
- {
- Console.Write(doubleArray[i, k] + " ");
- }
- Console.WriteLine();
- }
-
- Console.WriteLine();
- Console.WriteLine("Rank=" + doubleArray.Rank);
- Console.WriteLine("Elements=" + doubleArray.Length);
-
- Console.ReadKey();
- }
- }
- }
The output of the preceding program is as in the following:
Figure 1.4- Literal 2D Array