Arrays: A Brief Tutorial
Introduction
Arrays are powerful data structures that can be used to solve many programming problems. You have seen during the creation of different variables that they have one thing in common: they hold information about single items such as an integer, float, and string type. So what is the solution if you need to manipulate sets of items? One would be to create a variable for each item in the set, but again, this can lead to a different problem. How many variables do you actually 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. 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, general speaking, is an unordered sequence of elements. All the elements in an array have the same types (unlike the fields in class which have different types). The elements of array's access by using integer index is always start from zero. C# supports single-dimension (vectors), multidimensional and jagged arrays.
Elements are identified with indexes that are relative to beginning of the arrays. An index also is commonly called indices or subscripts and is placed inside the indexing operator ([]).They access array elements via their index value, which ranges from 0 to (length-1).
Array Properties
- The length cannot be changed once created.
- Elements are initialized to default values.
- Arrays are reference type and are instance of System.Arraynamespace.
- Their number of dimension or Rank can be determined by the Rank property.
-
Array length can be determined by the GetLength() method or Length property.
Simple Arrays Example
In the following example, we are declaring an Integer type array variable myArrays with length 5at line 10. Which means the myArrays variable can hold 5 integer elements. From line 15, we are accessing each elements using a 'for' loop and doing even number calculations over them. Finally at line 21, we are displaying each element.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace Arrays
{
classProgram
{
staticvoid Main(string[] args)
{
// Integer type array with length 5( range 0 to 4)
int[] myArrays = newint[5];
Console.WriteLine("Simple Array Example");
// Arrays inititalization
for (inti = 0; i<myArrays.Length; i++)
{
// Even number manipulation
myArrays[i] = i * 2;
// print array
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 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 above figure shows the array declaration and allocation syntax for a single-dimension array having a particular type and length. The declaration begins with the array element type. The element of an array can be 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 array.
To actually allocate memory for an array, use the new operator followed by the type of elements the array can contains 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 = newint[3];
The following line of code would simply declare an array of floats:
float[] myArrays;
And this code would allocate memory (initialize) to hold 6 float values:
myArrays=newfloat[6] ;
The following line of code would simply declare an array of strings:
String[] arry = newString[8];
You can also assign values to every array elements using an array initialize:
int[] arry = newint[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):
namespace Arrays
{
classProgram
{
staticvoid Main(string[] args)
{
// Integer type array with length 5( range 0 to 4)
int[] arry = newint[5];
Console.WriteLine("Type=" + arry.GetType());
Console.WriteLine("Rank=" + arry.Rank);
Console.WriteLine("Length=" + arry.Length);
Console.ReadKey();
}
}
}
Vector Array using Literal Values
Up 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 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 poses the concatenation of two words:
namespace Arrays
{
classProgram
{
staticvoid Main(string[] args)
{
// string type array with length 2( range 0 to 1)
string[] arry = {"Barack" , "Obama"};
//string concatenation
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 and then it iterates through with all the elements to find out 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 the each element, one by one, then it continue the loop; otherwise it changes the value of x by assigning the current element value. Finally, it prints the largest values.
namespace Arrays
{
classProgram
{
staticvoid Main(string[] args)
{
// Integer type array
int[] arry = {5,3,7,8,9};
int x=0;
for (inti = 0; i<arry.Length; i++)
{
if (x >arry[i])
{
continue;
}
else
{
x = arry[i];
}
}
Console.WriteLine("Largest Number=" + x);
Console.ReadKey();
}
}
}
Reference Type
Reference Type of arrays 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 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 with length 2 and finally printing the FirstName and LastName by iterating foreach loop as following;
namespace Arrays
{
publicclassCustomer
{
public Customer() { }
public Customer(stringfname,stringlname)
{
this.fname = fname;
this.lname = lname;
}
privatestringfname;
privatestringlname;
publicstringFirstName
{
get { returnfname; }
set { fname = value; }
}
publicstringLastName
{
get { returnlname; }
set { lname = value; }
}
publicoverridestringToString()
{
returnfname + " " + lname;
}
}
classProgram
{
staticvoid Main(string[] args)
{
Customer[] obj = newCustomer[2];
obj[0] = newCustomer("ajay","yadav");
obj[1] = newCustomer("tom","hanks");
foreach(Customeriinobj)
{
Console.WriteLine(i.ToString());
}
Console.ReadKey();
}
}
}
Array Exception Handling
Sometimes, unintentionally, there are glitches in the code that pertain to array index range. For example, in the following program we are calculating five numbers addition. So at line 5, in 'for' loop we are putting an equal sign in the condition. In that case the loop will execute 6 times rather 5 times; this eventually generates Index out of range error.
However, due to evading such coding glitches, we are putting the significant code into the try block and using the catch block, we are flashing an alert message for index out of range, as follows:
2
3
4
5
6
7
8
namespace Arrays
{
classProgram
{
staticvoid Main(string[] args)
{
// integer type array
int[] obj = newint[5] {1,2,3,4,5};
int Addition = 0;
//Index out of range checking
try
{
for (inti = 0; i<= obj.Length; i++)
{
Addition = Addition + obj[i];
}
}
catch(IndexOutOfRangeException err)
{
Console.WriteLine("Error! Array is out of Range"+err.Message);
}
finally
{
Console.WriteLine("Array Addition=" + Addition);
}
Console.ReadKey();
}
}
}
In order to run this program correctly, we have to write thecode as following:
for (inti = 0; i<obj.Length; i++)
{
Addition = Addition + obj[i];
}
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 array elements can be accessed by using two integers with the indexer.
Here, we are declaring a 2D array which has two rows and two columns and then assigning values:
// 2D integer type array
int[,] dArray = newint[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 row and columns. The following table depicts a 2 X 2 dimension of arrays with values in the corresponding row and columns, as following:
1
2
3
4
You can also initialize the 2D array by using an array indexer if you know the value for the elements in advance.
// 2D integer type array
int[,] dArray ={
{1,2,3},
{4,5,6}
};
The following program generates a double-dimension array grid by filling them with the values as well as calculating the total number of elements with ranks, as following:
namespace Arrays
{
classProgram
{
staticvoid Main(string[] args)
{
Console.WriteLine("Enter the Rank::");
int row = Int32.Parse(Console.ReadLine());
int cols = Int32.Parse(Console.ReadLine());
Console.WriteLine("__________________________");
int[,] doubleArray = newint[row, cols];
for (inti = 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 form of a matrix:
Figure 1.3- 2D Array
Rectangular arrays can be initialized using the literal values in an array initialize expression:
namespace Arrays
{
classProgram
{
staticvoid Main(string[] args)
{
char[,] doubleArray = {
{'A','B','C'},
{'D','E','F'},
{'G','H','I'}
};
for (inti = 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 above program will be as follows:
Figure 1.4- Literal 2D Array
11 courses, 8+ hours of training