|
You have selected free tutorial of the Microsoft Corporation for the Microsoft Technology Associate (MTA) :
98-361: MTA: Software Development Fundamentals (C#) : Module 1: Introduction to Programming :
UNDERSTANDING ARRAYS
Arrays are one of the collections that C# provides. But prior to reading a discussion of
arrays, you need a quick overview of collections. Collections are a standard set of classes
used to store and manage a group of objects. These classes are shown here:
- Array—A fixed size allocation of memory where data can be accessed randomly
using the integer subscript or index.
- ArrayList—A collection that behaves as a dynamic array. In other words, the size
can be dynamically increased as required. It can store objects of any derived type.
- List—Stores a strongly typed list of objects that index can access.
- Hashtable—A lookup data structure that uses a hash code to find elements
quickly. Therefore, a hashtable is considered an extremely efficient way to store
keys for lookup.
- Dictionary—A collection of keys and values that is an implementation of a
hashtable.
- Stack—Represents a LIFO (last in, first out) collection of objects. The procedure
for adding an item to the stack is called pushing, and that of removing an item is
called popping.
- Queue—Supports a FIFO (first in, first out) structure. The procedure for adding an
item in the queue is called enqueue, and removing an item in the queue is called
deque.
An array refers to a collection of values, usually of the same type, that is stored in
consecutive memory locations. The advantage of storing values in an array is that
you can access them randomly by specifying the index or subscript. An array can
store data of any type, including integer, float, and strings.
Arrays are of two types:
- One-dimensional
- Multidimensional
One-Dimensional Arrays
As the name suggests, one-dimensional arrays have either rows or columns to store
their values linearly. In C#, arrays are implemented as objects. To define an array,
you first declare a variable that refers to an array followed by creating an instance of
the array through the new operator. The syntax for defining a one-dimensional array is
given here:
data_type[] array_name = new data_type[size];
where data_type refers to the type of data that will be stored in the array and size in
square brackets refers to the allowable number of values that can be stored in the
array.
Following are the two ways to define an integer array p of size 10 elements:
int[] p = new int[10];
int[] p;
p = new int[10];
Program Code in OneDimArray.cs File
using System;
class OneDimArray{v
static void Main() {
int[] p = new int[10];
int i;
Console.WriteLine("Enter ten numbers");
for(i = 0; i <=9; i++)v
p[i] =Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nThe numbers entered in the array are");
for(i = 0; i <=9; i++)
Console.WriteLine(p[i]);
}
}
Output:
Enter ten numbers
4
0
9
1
3
6
2
8
5
7
The numbers entered in the array are
4
0
9
1
3
6
2
8
5
7
The memory to store 10 integers is allocated to array p. The user is asked to enter 10
integer values which, using the for loop, are stored in the specific index or subscript
location. For example, the first value the user enters is stored in index location p[0],
the second value in p[1], and so on. After the entered values are assigned and stored in
the respective memory allocated to the array p, each array element is accessed via its
index and displayed on the screen.
Initializing an Array
If the values for the array elements are known, you can use them to initialize the array
while creating it. The syntax for initializing a one-dimensional array is given here:
data_type[] array_name = { value1, value2, value3, ... , valueN };
The values value1, value2.... valueN are assigned to the array array_name to initialize it.
The values are assigned sequentially beginning with index value 0.
Example:
The following statement initializes an array p to 10 integer values. The values are
stored at index locations p[0], p[1]…… p[9].
int[] p = {4,0,2,8,1,7,3,9,5,6};
Because 10 blocks of memory are allocated to the array p, its Length property displays
10.
Program Code in ArrayInit.cs File
using System;
class ArrayInit{
static void Main() {
int[] p = {4,0,2,8,1,7,3,9,5,6};
int i;
Console.WriteLine("The numerals entered in the array are");
for(i = 0; i
Console.WriteLine(p[i]);
}
}
Output:
The numerals entered in the array are
4
0
2
8
1
7
3
9
5
6
The values 4, 0, 2, 8, 1, 7, 3, 9, 5, and 6 are assigned to the array p for initializing it as
shown in Figure 5.2. The first value is assigned to index location p[0], the second to
p[1], and so on. The Length property of the array represents value 10, so a for loop is
set to execute from 0 until one less than the Length property to access and display all
array elements.
Using the foreach Loop
The foreach loop cycles through the elements of a collection. Here’s the syntax for
using the foreach loop:
foreach(data_type variable in collection) statement;
where data_type variable specifies the data type of an iteration variable. The iteration
variable accesses the value of the next element in the collection each time the foreach
loop is executed. Because the element of the collection is assigned to the iteration variable,
its data type must match the data type of the collection.
You’ll use the foreach loop to access and display array elements. The ArrayForEach.cs
program shown below initializes an array with 10 numerical values and displays
its elements using the foreach loop. The program also sorts the array and redisplays
the sorted values.
Program Code in ArrayForEach.cs File
using System;
class ArrayForEach{
static void Main() {
int[] p = {4,0,2,8,1,7,3,9,5,6};
Console.WriteLine("The original order of numerals in the array is:");
foreach(int x in p) {
Console.WriteLine(x);
}
Array.Sort (p);
Console.WriteLine("\nThe array in sorted order is: ");
foreach(int x in p) {
Console.WriteLine(x);
}
}
}
The first element in the array p is assigned to iteration variable x, which is then displayed.
With each subsequent iteration of the foreach loop, the next element from the
array p is accessed and assigned to the variable x. For example, in the first iteration,
value 4 is assigned to variable x, which is subsequently displayed on the screen. In the
next iteration, the second value 0 is assigned to the variable x and hence displayed on
the screen. The iteration of the foreach loop terminates when all the elements of the
array are accessed.
For sorting, the Array class has the built-in Sort() method that sorts an entire array.
The Sort() method requires the array to contain built-in C# types like int and string.
In the preceding code, the array p is sorted by passing it to the Sort() method, and the
sorted elements are then displayed on the screen.
Output:
The original order of numerals in the array is:
4
0
2
8
1
7
3
9
5
6
The array in sorted order is:
0
1
2
3
4
5
6
7
8
9
A one-dimensional array contains either rows or columns. Now you’ll read about
arrays that have both.
Two-Dimensional Arrays
In a two-dimensional array, the array elements are arranged in rows as well as in columns
fashion. That is, the elements are arranged in tabular form and hence are stored
and accessed by using two indices: one refers to the row and the other refers to the
column location.
Here’s the syntax for defining a two-dimensional array:
data_type[,] array_name = new data_type[size1, size2];
where [,] indicates that a two-dimensional array reference variable is being defined.
The size1 and size2 refer to the number of rows and columns in the array,
respectively.
Example:
int [,] p=new int[2][4];
The preceding command defines an array p consisting of two rows and four columns.
The indices by which the array elements of this two-dimensional array
To access an array element, you need to specify both row and column indices, as
shown here:
k=p[1][2];
By the preceding statement, the array element at row 1 and column 2 location will be
accessed and assigned to variable k. Now you’ll quickly write a program that defines a
two-dimensional integer array. The program TwoDimArray.cs, shown below,
prompts the user to enter a few integers that will be stored in a two-dimensional
array sized 2 by 4. The array elements are then displayed on the screen.
Program Code in TwoDimArray.cs File
using System;
class TwoDimArray {
static void Main() {
int[,] p = new int[2, 4];
int i,j;
Console.WriteLine("Enter elements for an array of order 2 x 4");
for(i = 0; i <=1; i++)
{
for(j = 0; j <=3; j++)
{
p[i,j] =Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("\nThe elements in the two-dimensional array are");
for(i = 0; i <=1; i++)
{
for(j = 0; j <=3; j++)
{
Console.Write(p[i,j]+"\t");
}
Console.WriteLine();
}
}
}
Output:Enter elements for an array of order 2 x 4
4
3
9
1
2
6
8
5
The elements in the two-dimensional array are
4 3 9 1
2 6 8 5
The values are stored in the array in "row major" form by default. "Row major" form
means that the first row is filled, followed by the second row, and so on. In other
words, the values the user enters are sequentially stored in the first row of the twodimensional
array (in p[0][0], p[0][1], p[0][2], and p[0][3] locations). After you fill
the first row, values are stored in the second row (in p[1][0], p[1][1], p[1][2], and
p[1][3] locations).
The next section discusses strings, which are an array of characters.
Multidimensional Arrays
A multidimensional array is an array that has two or more dimensions. In other
words, its elements are stored and retrieved through a combination of two or more
indices. The most popular multidimensional array is a two-dimensional array.
|
Your Salary Above $ 66000... Click ...
Ohh! You want More.... be game developer of your choice $ 102000 ....
|