Array in C# .Net
Why array?
As we know that variable store only single value at same time. If we want to store multiple values this is not possible, because when we assign new value to variable old value loss.
Examle:-
using System;
class ArrayDemo
{
static void Main()
{
int x = 3030;
x = 3033; //x=3030 is loss
Console.WriteLine("The value of x="+x);
x = 321; //x=3033 loss
Console.WriteLine("The value of x="+x);
Console.ReadLine();
}
}
But user wants to store all three values in above program. How is it possible? For this a concept is developed this concept is called ‘Array’.
So, what is array? Array is the old memorization of data. By array we achieved specialization data. Many teachers and programmers are saying array is collection of similar data type. Yes they are right. Because we store multiples data but single type data at the same time.
I give real life example to my mother. My mother is 50 years old. She has photo book let of her photos collection from childhood to up to date. By this photos book let, I know, how was my mother looking beautiful at childhood, young and present time. Same concept is come at ‘array’ also.
Array is class for similar type of data. Array runs on heap memory. The principal advantage of an array is that it organizes data in such a way that it can be easily manipulated. For example, if you have an array containing the dividends for a selected group of stocks, it is easy to compute the average income by cycling through the array. Also, arrays organize data in such a way that it can be easily sorted.
Although arrays in C# can be used just like arrays in many other programming languages, they have one special attribute: They are implemented as objects. This fact is one reason that a discussion of arrays was deferred until objects had been introduced. By implementing arrays as objects, several important advantages are gained, not the least of which is that unused arrays can be garbage-collected.
Type of array:-
Array has three types-
1. Single-Dimensional array
2. Multi-Dimensional array
3. Jagged array
Single-Dimensional array:-
A one-dimensional array is a list of related variables. Such lists are common in programming. For example, you might use a one dimensional array to store the account numbers of the active users on a network. Another array might store the current batting averages for a baseball team. Because arrays in C# are implemented as objects, two steps are needed to obtain an array for use in your program. First, you must declare a variable that can refer to an array. Second, you must create an instance of the array by use of new. Therefore, to declare a one-dimensional array, you will typically use this general form:
type[ ] array-name = new type[size];
Here, type declares the element type of the array. The element type determines the data type of each element that comprises the array. Notice the square brackets that follow type. They indicate that a one-dimensional array is being declared. The number of elements that the
array will hold is determined by size.
NOTE If you come from a C or C++ background, pay special attention to the way arrays are
declared. Specifically, the square brackets follow the type name, not the array name. Here is an example. The following creates an int array of ten elements and links it to an array reference variable named sample.
int[] sample = new int[10];
The sample variable holds a reference to the memory allocated by new. This memory is large enough to hold ten elements of type int.
As is the case when creating an instance of a class, it is possible to break the preceding declaration in two. For example:
int[] sample;
sample = new int[10];
In this case, when sample is first created, it refers to no physical object. It is only after the second statement executes that sample refers to an array. An individual element within an array is accessed by use of an index. Anindex describes the position of an element within an array. In C#, all arrays have 0 as the index of their first element. Because sample has 10 elements, it has index values of 0 through 9. To index an
array, specify the number of the element you want, surrounded by square brackets. Thus, the first element insample is sample[0], and the last element is sample[9]. For example, the following program loads sample with the numbers 0 through 9:
// Demonstrate a one-dimensional array.
using System;
class ArrayDemo
{
static void Main()
{
int[] sample = new int[10];
int i;
for (i = 0; i < 10; i = i + 1)
sample[i] = i;
for (i = 0; i < 10; i = i + 1)
Console.WriteLine("sample[" + i + "]: " + sample[i]);
Console.ReadLine();
}
}
The output from the program is shown here:-
sample[0]: 0
sample[1]: 1
sample[2]: 2
sample[3]: 3
sample[4]: 4
sample[5]: 5
sample[6]: 6
sample[7]: 7
sample[8]: 8
sample[9]: 9
Conceptually, the sample array looks like this:
Image--------------single array………………..
Arrays are common in programming because they let you deal easily with large numbers of related variables. For example, the following program finds the average of the set of values stored in the nums array by cycling through the array using a for loop:
// Compute the average of a set of values.
using System;
class AverageDemo
{
static void Main()
{
int[] nums = new int[10];
int avg = 0;
nums[0] = 99;
nums[1] = 10;
nums[2] = 100;
nums[3] = 18;
nums[4] = 78;
nums[5] = 23;
nums[6] = 63;
nums[7] = 9;
nums[8] = 87;
nums[9] = 49;
for (int i = 0; i < 10; i++)
avg = avg + nums[i];
avg = avg / 10;
Console.WriteLine("Average: " + avg);
Console.ReadLine();
}
}
The output from the program is shown here:
Average: 53
Initializing an Array
In the preceding program, the nums array was given values by hand,using ten separate assignment statements. While that is perfectly correct, there is an easier way to accomplish this. Arrays can be initialized when they are created. The general form for initializing a onedimensional array is shown here:
type[ ] array-name = { val1, val2, val3, ..., valN };
Here, the initial values are specified by val1 through valN. They are assigned in sequence, left to right, in index order. C# automatically allocates an array large enough to hold the initializers that you specify. There is no need to use the new operator explicitly.
For example, here is a better way to write the Average program:
// Compute the average of a set of values.
using System;
class AverageDemo
{
static void Main()
{
int[] nums = { 99, 10, 100, 18, 78, 23,63, 9, 87, 49 };
int avg = 0;
for (int i = 0; i < 10; i++)
avg = avg + nums[i];
avg = avg / 10;
Console.WriteLine("Average: " + avg);
Console.ReadLine();
}
}
As a point of interest, although not needed, you can use new when initializing an array. For example, this is a proper, but redundant, way to initialize nums in the foregoing program:
int[] nums = new int[] { 99, 10, 100, 18, 78, 23, 63, 9, 87, 49 };
Although redundant here, the new form of array initialization is useful when you are assigning a new array to an already-existent array reference variable. For example:
int[] nums;
nums = new int[] { 99, 10, 100, 18, 78, 23,63, 9, 87, 49 };
In this case, nums is declared in the first statement and initialized by the second. One last point: It is permissible to specify the array size explicitly when initializing an array, but the size must agree with the number of initializers. For example, here is another way to initialize nums:
int[] nums = new int[10] { 99, 10, 100, 18, 78, 23, 63, 9, 87, 49 };
In this declaration, the size of nums is explicitly stated as 10.
Boundaries Are Enforced
Array boundaries are strictly enforced in C#; it is a runtime error to overrun or underrun the ends of an array. If you want to confirm this for yourself, try the following program that purposely overruns an array:
// Demonstrate an array overrun.
using System;
class ArrayErr
{
static void Main()
{
int[] sample = new int[10];
int i;
// Generate an array overrun.
for (i = 0; i < 100; i = i + 1)
sample[i] = i;
Console.ReadLine();
}
}
As soon as i reaches 10, an IndexOutOfRangeException is generated and the program is
terminated. (See exceptions and exception handling for details.)
2. Multidimensional Arrays
Although the one-dimensional array is the most commonly used array in programming, multidimensional arrays are certainly not rare. A multidimensional array is an array that has two or more dimensions, and an individual element is accessed through the combination of two or more indices.
Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. In a two dimensional array, the location of any specific element is specified by two indices. If you think of a two-dimensional array as a table of information, one index indicates the row, the other indicates the column. To declare a two-dimensional integer array table of size 10, 20, you would write
int[,] table = new int[10, 20]; Pay careful attention to the declaration. Notice that the two dimensions are separated from each other by a comma. In the first part of the declaration, the syntax [,]
indicates that a two-dimensional array reference variable is being created. When memory is actually allocated for the array using new, this syntax is used:
int[10, 20]
This creates a 10×20 array, and again, the comma separates the dimensions.
To access an element in a two-dimensional array, you must specify both indices, separating the two with a comma. For example, to assign the value 10 to location 3, 5 of array table, you would use table[3, 5] = 10;
Here is a complete example. It loads a two-dimensional array with the numbers 1 through 12 and then displays the contents of the array.
// Demonstrate a two-dimensional array.
using System;
class TwoD
{
static void Main()
{
int t, i;
int[,] table = new int[3, 4];
for (t = 0; t < 3; ++t)
{
for (i = 0; i < 4; ++i)
{
table[t, i] = (t * 4) + i + 1;
Console.Write(table[t, i] + " ");
}
Console.WriteLine();
Console.ReadLine();
}
}
}
In this example, table[0, 0] will have the value 1, table[0, 1] the value 2, table[0, 2] the value 3, and so on. The value of table[2, 3] will be 12. Conceptually, the array will look like the one shown in Figure 7-1.
NOTE If you have previously programmed in C, C++, or Java, be careful when declaring or accessing multidimensional arrays in C#. In these other languages, array dimensions and indices are specified within their own set of brackets. C# separates dimensions using commas.
Arrays of Three or More Dimensions
C# allows arrays with more than two dimensions. Here is the general form of a multidimensional array declaration:
type[, ...,] name = new type[size1, size2, ..., sizeN];
FIGURE 7-1
A conceptual view
of the table array
created by the
TwoD program
::::::::::::::::::::::::::::::::::::image multi dimen
For example, the following declaration creates a 4×10×3 three-dimensional integer array: int[,,] multidim = new int[4, 10, 3];
To assign element 2, 4, 1 of multidim the value 100, use this statement:
multidim[2, 4, 1] = 100;
Here is a program that uses a three-dimensional array that holds a 3×3×3 matrix of values. It then sums the value on one of the diagonals through the cube.
// Sum the values on a diagonal of a 3x3x3 matrix.
using System;
class ThreeDMatrix
{
static void Main()
{
int[, ,] m = new int[3, 3, 3];
int sum = 0;
int n = 1;
for (int x = 0; x < 3; x++)
for (int y = 0; y < 3; y++)
for (int z = 0; z < 3; z++)
m[x, y, z] = n++;
sum = m[0, 0, 0] + m[1, 1, 1] + m[2, 2, 2];
Console.WriteLine("Sum of first diagonal: " + sum);
Console.ReadLine();
}
}
The output is shown here:
Sum of first diagonal: 42
Initializing Multidimensional Arrays
A multidimensional array can be initialized by enclosing each dimension’s initializer list within its own set of curly braces. For example, the general form of array initialization for a two-dimensional array is shown here:
type[,] array_name = {
{ val, val, val, ..., val },
{ val, val, val, ..., val },
...
{ val, val, val, ..., val }
};
Here, val indicates an initialization value. Each inner block designates a row. Within each row, the first value will be stored in the first position, the second value in the second position, and so on. Notice that commas separate the initializer blocks and that a semicolon follows the closing }.
For example, the following program initializes an array called sqrs with the numbers 1 through 10 and their squares.
// Initialize a two-dimensional array.
using System;
class Squares
{
static void Main()
{
int[,] sqrs = {
{ 1, 1 },
{ 2, 4 },
{ 3, 9 },
{ 4, 16 },
{ 5, 25 },
{ 6, 36 },
{ 7, 49 },
{ 8, 64 },
{ 9, 81 },
{ 10, 100 }
};
int i, j;
for (i = 0; i < 10; i++)
{
for (j = 0; j < 2; j++)
Console.Write(sqrs[i, j] + " ");
Console.WriteLine();
Console.ReadLine();
}
}
}
Here is the output from the program:
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 00
3.Jagged Arrays:-
In the preceding examples, when you created a two-dimensional array, you were creating what is called arectangular array. Thinking of two-dimensional arrays as tables, a rectangular array is a two-dimensional array in which the length of each row is the same for the entire array. However, C# also allows you to create a special type of two-dimensional array called a jagged array. A jagged array is an array of arrays in which the length of each array can differ. Thus, a jagged array can be used to create a table in which the lengths of the rows are not the same.
Jagged arrays are declared by using sets of square brackets to indicate each dimension. For example, to declare a two-dimensional jagged array, you will use this general form:
type[ ] [ ] array-name = new type[size][ ];
Here, size indicates the number of rows in the array. The rows, themselves, have not been
allocated. Instead, the rows are allocated individually. This allows for the length of each row to vary. For example, the following code allocates memory for the first dimension of jagged when it is declared. It then allocates the second dimensions manually.
int[][] jagged = new int[3][];
jagged[0] = new int[4];
jagged[1] = new int[3];
jagged[2] = new int[5];
After this sequence executes, jagged looks like this:
:::::::::::::::::::::::::::::::::::::::::::::::image jagged arra::::::::::::::
It is easy to see how jagged arrays got their name! Once a jagged array has been created, an element is accessed by specifying each index within its own set of brackets. For example, to assign the value 10 to element 2, 1 ofjagged, you would use this statement:
jagged[2][1] = 10;
Note that this differs from the syntax that is used to access an element of a rectangular array. The following program demonstrates the creation of a jagged two-dimensional array:
// Demonstrate jagged arrays.
using System;
class Jagged
{
static void Main()
{
int[][] jagged = new int[3][];
jagged[0] = new int[4];
jagged[1] = new int[3];
jagged[2] = new int[5];
int i;
// Store values in first array.
for (i = 0; i < 4; i++)
jagged[0][i] = i;
// Store values in second array.
for (i = 0; i < 3; i++)
jagged[1][i] = i;
// Store values in third array.
for (i = 0; i < 5; i++)
jagged[2][i] = i;
// Display values in first array.
for (i = 0; i < 4; i++)
Console.Write(jagged[0][i] + " ");
Console.WriteLine();
// Display values in second array.
for (i = 0; i < 3; i++)
Console.Write(jagged[1][i] + " ");
Console.WriteLine();
// Display values in third array.
for (i = 0; i < 5; i++)
Console.Write(jagged[2][i] + " ");
Console.WriteLine();
Console.ReadLine();
}
}
The output is shown here:
0 1 2 3
0 1 2
0 1 2 3 4
Jagged arrays are not used by all applications, but they can be effective in some situations. For example, if you need a very large two-dimensional array that is sparsely populated (that is, one in which not all of the elements will be used), then a jagged array might be a perfect solution. One last point: Because jagged arrays are arrays of arrays, there is no restriction that requires that the arrays be one-dimensional. For example, the following creates an array of two-dimensional arrays:
int[][,] jagged = new int[3][,];
The next statement assigns jagged[0] a reference to a 4×2 array:
jagged[0] = new int[4, 2];
The following statement assigns a value to jagged[0][1,0]:
jagged[0][1,0] = i;
Assigning Array References
As with other objects, when you assign one array reference variable to another, you are simply making both variables refer to the same array. You are neither causing a copy of the array to be created, nor are you causing the contents of one array to be copied to the other.
For example, consider this program:
// Assigning array reference variables.
using System;
class AssignARef
{
static void Main()
{
int i;
int[] nums1 = new int[10];
int[] nums2 = new int[10];
for (i = 0; i < 10; i++) nums1[i] = i;
for (i = 0; i < 10; i++) nums2[i] = -i;
Console.Write("Here is nums1: ");
for (i = 0; i < 10; i++)
Console.Write(nums1[i] + " ");
Console.WriteLine();
Console.Write("Here is nums2: ");
for (i = 0; i < 10; i++)
Console.Write(nums2[i] + " ");
Console.WriteLine();
nums2 = nums1; // now nums2 refers to nums1
Console.Write("Here is nums2 after assignment: ");
for (i = 0; i < 10; i++)
Console.Write(nums2[i] + " ");
Console.WriteLine();
// Next, operate on nums1 array through nums2.
nums2[3] = 99;
Console.Write("Here is nums1 after change through nums2: ");
for (i = 0; i < 10; i++)
Console.Write(nums1[i] + " ");
Console.WriteLine();
Console.ReadLine();
}
}
The output from the program is shown here:
Here is nums1: 0 1 2 3 4 5 6 7 8 9
Here is nums2: 0 -1 -2 -3 -4 -5 -6 -7 -8 -9
Here is nums2 after assignment: 0 1 2 3 4 5 6 7 8 9
Here is nums1 after change through nums2: 0 1 2 99 4 5 6 7 8 9
As the output shows, after the assignment of nums1 to nums2, both array reference
variables refer to the same object.
Using the Length Property
A number of benefits result because C# implements arrays as objects. One comes from the fact that each array has associated with it a Length property that contains the number of elements that an array can hold. Thus, each array provides a means by which its length can be determined. Here is a program that demonstrates this property:
// Use the Length array property.
using System;
class LengthDemo
{
static void Main()
{
int[] nums = new int[10];
Console.WriteLine("Length of nums is " + nums.Length);
// Use Length to initialize nums.
for (int i = 0; i < nums.Length; i++)
nums[i] = i * i;
// Now use Length to display nums.
Console.Write("Here is nums: ");
for (int i = 0; i < nums.Length; i++)
Console.Write(nums[i] + " ");
Console.WriteLine();
Console.ReadLine();
}
}
This program displays the following output:
Length of nums is 10
Here is nums: 0 1 4 9 16 25 36 49 64 81
No comments:
Post a Comment