Creating
Arrays
An
array is a single data variable that can store multiple pieces of data that are
each of the same data type.
To
declare an array, you use the square brackets after the data type when you
declare the
variable.
The basic format of an array declaration is as shown here:
datatype[] name;
datatype
is the type for the information you will store. The square brackets indicate
that you are declaring an array, and the name is the name of the array
variable. The following definition sets up an array variable called num that
can hold integer values:
int[] num;
This
declaration creates the variable and prepares it to be capable of holding
integer values;
however,
it doesn’t actually set aside the area to hold the variables. To do that, you
need to do the same thing you do to create other objects, which is to
initialize the variable using the new keyword. When you instantiate the array,
you must indicate how many values will be stored. One way to indicate this
number is to include the number of elements in square brackets when you do the
initialization:
num = new int[10];
You
also can do this initialization at the same time that you define the variable:
int[] num = new
int[10];
As
you can see, the format for initializing is as follows:
new
datatype[nbr_of_elements]
datatype
is the same data type of the array, and nbr_of_elements is a numeric value that
indicates the number of items to be stored in the array. In the case of the num
variable, you can see that 10 integers values can be stored.
Simple
program to implement an array-
using System;
class Program
{
public static void Main()
{
int[]
num = new int[10];
Console.WriteLine("Enter the integer numbers");
for
(int i = 0; i < 10; i++)
{
num[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Numbers you have entered are");
for
(int i = 0; i < 10; i++)
{
Console.WriteLine(num[i]);
}
}
}
Initializing
Array Elements
You
can initialize the values of the individual array elements at the same time
that you declare and initialize the array. You can do this by declaring the
values after the array declaration. The values are enclosed in a block and are
separated by a comma.
char[] name = new
char[6] { 'A', 'd', 'i', 't', 'y', 'a' };
It is interesting to note that if you initialize the values
in this manner, you do not have to include the array size in the brackets. The
following statement is equivalent to the previousstatement:
char[] name = new
char[] { 'A',
'd', 'i', 't', 'y', 'a' };
or
char[] name = { 'A', 'd', 'i', 't', 'y', 'a' };
The compiler automatically defines this array
as 6 elements because that is the number of items being initialized. The
following program creates and initializes a character array.
using System;
class Program
{
public static void Main()
{
char[] name = new char[] {'A','d','i','t','y','a', (char) 0 };
Console.WriteLine("Display content of name array...");
int
i = 0;
while (name[i]
!= 0)
{
Console.Write("{0}", name[i]);
i++;
}
Console.WriteLine("\nDone.....");
}
}
Working
with Multidimensional Arrays
A multidimensional array is an array of arrays. You can even have an array
of arrays of arrays. The number of levels can quickly add up. This starts
getting complicated, so I recommend that you don’t store more than three levels
(or three dimensions) of arrays.
An array of arrays is often referred to as a two-dimensional array because
it can be represented
in two dimensions. To declare a two-dimensional array, you expand on what
you do with a regular (or one-dimensional) array:
byte[,] scores = new byte[15,30];
A comma is added to the first part of the declaration, and two numbers
separated by a command are used in the second part. This declaration creates a
two-dimensional array that has 15 elements, each containing an array of 30
elements. In total, the scores array holds 450 values of the data type byte. To
declare a simple multidimensional array that stores a few characters, you enter
the following:
char[,] letters = new char[2,3]; // without initializing values
This declaration
creates a two-dimensional array called letters, which contains two elements
that are each arrays that have three character elements. You can initialize the
elements within the letters array at declaration time:
char[,] letters
= new char[,] { {‘a’,’b’,’c’},{‘X’,’Y’,’Z’} };
Or, you can
initialize each element individually. To access the elements of a
multidimensional array, you again use the indexes. The first element of the
letters array is letters[0,0]. Remember, the indexes start at offset 0, not 1.
letters[0,1] is the second element, which contains the letter ‘b’. The letter
‘X’ is letter[1,0] because it is in the second array (offset 1) and is the
first element (offset 0). To initialize the letters array outside the
declaration, you could do the following:
letters[0,0] =
‘a’;
letters[0,1] = ‘b’;
letters[0,2] =
‘c’;
letters[1,0] =
‘X’;
letters[1,1] =
‘Y’;
letters[1,2] =
‘Z’;
Creating an
Array Containing Different-Size Arrays
In the previous
section, an assumption was made that in a two-dimensional array, all the subarrays
are the same size. This would make the arrays rectangular. What happens if you
want to store arrays that are not the same size? Consider the following:
char[][] myname
= new char[3][];
myname[0] = new
char[] { ‘A’, ‘d’, ‘i’, ‘t’, ‘y’, ‘a’,};
myname[1] = new
char[] { ‘K’, ‘.’ };
myname[2] = new
char[] { ‘T’, ‘y’, ‘a’, ‘g’, ‘i’ };
The myname array
is an array of arrays. It contains three character arrays that are each a different
length. Because they are different lengths, you work with their elements
differently from the rectangular arrays that you saw before.
Instead
of addressing each element by using index values separated by commas, you instead
separate the elements into their own square brackets. For example, the
following line of code uses the WriteLine method to print the array elements
that would be my initials:
System.Console.WriteLine(“{0}{1}{2}”,
myname[0][0], myname[1][0], myname[2][0]);
It would be
wrong to address these as myname[0,0], myname[1,0], and myname[2,0]. In fact,
you’ll get an
error if you try to access the elements this way.
What happens if
you want to declare the myname array without initializing it, as was done previously?
You know there are three parts to the name, so the first dimension is 3;
however,
what should the
second dimension be? Because of the variable sizes, you must make multiple
instantiations to set up the full array. First, you declare the outside array that
will hold the arrays:
char[][] myname
= new char[3][];
This declares
the myname variable as an array with three elements, each holding a character
array. After
you’ve done this declaration, you must initialize each of the individual arrays
that will be stored in myname[].
myname[0] = new
char[6]; // first array of six elements
myname[1] = new
char[2]; // second array of two elements
myname[2] = new
char[5]; // third array of five elements
Using a Jagged Two-Dimensional
Array:
using System;
public class Names
{
public static void Main()
{
char[][] name
= new char[3][];
name[0] = new char[6] {'A', 'd', 'i', 't', 'y', 'a'};
name[1] = new char[2] {'K', '.'};
name[2] = new char[5] {'T', 'y', 'a', 'g', 'i'};
Console.WriteLine("Display the sizes of the arrays...\n");
Console.WriteLine("Length of name array {0}", name.Length);
for( int ctr = 0; ctr < name.Length; ctr++)
Console.WriteLine("Length of name[{0}] is {1}",ctr,
name[ctr].Length);
//---------------------------------------------------------------------
Console.WriteLine("\nDisplaying the content of the name array...");
for( int ctr = 0; ctr < name.Length; ctr++)
{
Console.Write("\n"); // new
line
for( int ctr2 = 0; ctr2 < name[ctr].Length; ctr2++ )
{
Console.Write("{0}", name[ctr][ctr2]);
}
}
Console.WriteLine("\n...Done displaying");
}
}
A
multidimensional array that contains subarrays of the same size is referred to
as rectangular. A
multidimensional array that has variable-size subarrays stored is referred to
as “jagged.”
The System.Array
Class
In
C# every array we create is automatically derived from the System.Array class.
This class defines a number of methods and properties that can be used to
manipulate arrays more efficiently. The following table lists some of the
commonly used methods and their purpose.
Method/Property
|
Description
|
Clear()
CopyTo()
GetLength()
GetValue()
Length
SetValue()
Reverse()
Sort()
|
Sets a Range of Elements to empty
values
Copies elements from the source array
into the destination array
Gives the number of elements in a
given dimension of the array
Gets the value for a given index in
the array
Gives the length of an array
Sets the value for a given index in
the array
Reverse the contents of one
dimensional array
Sorts the elements in one dimensional
array
|
Using
GetLength()
int[] num = new
int[] { 1, 2, 3, 4, 5, 6, 7 };
int
dim= num.GetLength(0);//GetLength(int dimension)
Console.WriteLine(dim);//output
will be 7
int[,] num1 = new
int[2, 3];
Console.WriteLine(
num1.GetLength(0));//output will be 2
Console.WriteLine(
num1.GetLength(1));//output will be 3
Using
GetValue()
int[] num = new
int[] { 1, 2, 3, 4, 5, 6, 7 };
int val = (int)num.GetValue(3);//GetValue(int index)
Console.WriteLine(val);//output will be 4
Using
SetValue()
int[] num = new
int[] { 1, 2, 3, 4, 5, 6, 7 };
num.SetValue(12, 4);//SetValue(object value,int index)
Console.WriteLine(num[4]);//output
will be 12
Using
Sort()
int[] num = new int[]
{ 4, 2, 6, 3, 5, 1, 9 };
Array.Sort(num);
for (int
i = 0; i < num.Length; i++)
{
Console.Write(num[i]);
}
Output will be 1234569
Using
Reverse()
int[] num = new
int[] { 1, 2, 3, 4, 5, 6, 7 };
Array.Reverse(num);
for (int
i = 0; i < num.Length; i++)
{
Console.Write(num[i]);
}
Output will be 7654321
Using
Clear()
int[] num = new int[] { 1, 2, 3,
4, 5, 6, 7 };
Array.Clear(num, 0, 3);//Clear(Array
array,Int index,int length)
for (int i = 0; i < num.Length; i++)
{
Console.Write(num[i]);
}
Output will be 0004567