3.1 Introduce the arrays and its usage
An array is a group of contiguous or related data items that share a common name. For instance, we can define an array name marks to represent a set of marks of a class of students. A particular value is indicated by writing a number called index number or subscript in brackets after the array name.
Usage:
You can store multiple values in a single variable by using array in C#.
3.2 Demonstrate the declaration and initialization of array
Declaration:
Syntax:
type[] arrayname;
Examples:
int[] counter; //declare int array reference
float[] x,y;
Creation:
After declaring an array, we need to create it in the memory. C# allows us to create arrays using new operator only.
Syntax:
arrayname new type[size];
Examples:
number new int[5]; //create a 5 element int array
average new float[10]; // create a 10 element float array
Initialization:
Initialization of Arrays
This process is known as initialization.
Syntax:
arrayname[subscript] = value;
Example:
number[0] = 26;
number[1] = 19;
number[2] = 0;
number[3] = 22;
number[4] = 18;
Note that C# creates arrays starting with a subscript of 0 and ends with a value one less than the size specified.
We can also initialize arrays automatically in the same way as the ordinary variables when they are declared, as shown below:
type [] arrayname = {list of values);
Example:
int[] number [35, 40, 20, 57, 19};
3.3 Illustrate the data access from an array
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example,
double salary = balance[9];
Code:
using System;
namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
int [] n = new int[10]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100;
}
/* output each array element’s value */
for (j = 0; j < 10; j++ ) {
Console.WriteLine(“Element[{0}] = {1}”, j, n[j]);
}
Console.ReadKey();
}
}
}
Example:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
3.4 Introduce to multidimensional arrays
C# allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array. You can declare a 2-dimensional array of strings as −
string [,] names;
or, a 3-dimensional array of int variables as −
int [ , , ] m;
Two-Dimensional Arrays
The simplest form of the multidimensional array is the 2-dimensional array. A 2-dimensional array is a list of one-dimensional arrays.
A 2-dimensional array can be thought of as a table, which has x number of rows and y number of columns. Following is a 2-dimensional array, which contains 3 rows and 4 columns:
Thus, every element in the array a is identified by an element name of the form a[ i , j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in array a.
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for each row. The Following array is with 3 rows and each row has 4 columns.
int [,] a = new int [3,4] {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
Accessing Two-Dimensional Array Elements
An element in 2-dimensional array is accessed by using the subscripts. That is, row index and column index of the array.
Syntax:
int val = a[2,3];
Code:
using System;
namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
/* an array with 5 rows and 2 columns*/
int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
int i, j;
/* output each array element’s value */
for (i = 0; i < 5; i++) {
for (j = 0; j < 2; j++) {
Console.WriteLine(“a[{0},{1}] = {2}”, i, j, a[i,j]);
}
}
Console.ReadKey();
}
}
}
Output:
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8
3.5 Compare and deduce the applications of jagged arrays, param arrays, and array class
- Jagged Arrays
A Jagged array is an array of arrays. You can declare a jagged array named scores of type int as −
int [][] scores;
Declaring an array, does not create the array in memory. To create the above array −
int[][] scores = new int[5][];
for (int i = 0; i < scores.Length; i++) {
scores[i] = new int[4];
}
You can initialize a jagged array as −
int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};
Where, scores is an array of two arrays of integers – scores[0] is an array of 3 integers and scores[1] is an array of 4 integers.
Example:
using System;
namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
/* a jagged array of 5 array of integers*/
int[][] a = new int[][]{new int[]{0,0},new int[]{1,2},
new int[]{2,4},new int[]{ 3, 6 }, new int[]{ 4, 8 } };
int i, j;
/* output each array element’s value */
for (i = 0; i < 5; i++) {
for (j = 0; j < 2; j++) {
Console.WriteLine(“a[{0}][{1}] = {2}”, i, j, a[i][j]);
}
}
Console.ReadKey();
}
}
}
Output:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
- Parma Array
At times, while declaring a method, you are not sure of the number of arguments passed as a parameter. C# param arrays (or parameter arrays) come into help at such times.
Code:
using System;
namespace ArrayApplication {
class ParamArray {
public int AddElements(params int[] arr) {
int sum = 0;
foreach (int i in arr) {
sum += i;
}
return sum;
}
}
class TestClass {
static void Main(string[] args) {
ParamArray app = new ParamArray();
int sum = app.AddElements(512, 720, 250, 567, 889);
Console.WriteLine(“The sum is: {0}”, sum);
Console.ReadKey();
}
}
}
Output:
The sum is: 2938
- Array Class
The Array class is the base class for all the arrays in C#. It is defined in the System namespace. The Array class provides various properties and methods to work with arrays.
Properties of the Array Class
The following table describes some of the most commonly used properties of the Array class –
Sr.No. | Property & description |
1 | IsFixedSize Gets a value indicating whether the Array has a fixed size. |
2 | IsReadOnly Gets a value indicating whether the Array is read-only. |
3 | Length Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array. |
4 | LongLength Gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array. |
5 | Rank Gets the rank (number of dimensions) of the Array. |
Methods of the Array Class
The following table describes some of the most commonly used methods of the Array class −
Sr.No. | Methods & Description |
1 | Clear Sets a range of elements in the Array to zero, to false, or to null, depending on the element type. |
2 | Copy(Array, Array, Int32) Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 32-bit integer. |
3 | CopyTo(Array, Int32) Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index. The index is specified as a 32-bit integer. |
4 | GetLength Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array. |
5 | GetLongLength Gets a 64-bit integer that represents the number of elements in the specified dimension of the Array. |
6 | GetLowerBound Gets the lower bound of the specified dimension in the Array. |
7 | GetType Gets the Type of the current instance. (Inherited from Object.) |
8 | GetUpperBound Gets the upper bound of the specified dimension in the Array. |
9 | GetValue(Int32) Gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer. |
10 | IndexOf(Array, Object) Searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array. |
11 | Reverse(Array) Reverses the sequence of the elements in the entire one-dimensional Array. |
12 | SetValue(Object, Int32) Sets a value to the element at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer. |
13 | Sort(Array) Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array. |
14 | ToString Returns a string that represents the current object. (Inherited from Object.) |
Code:
using System;
namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
int[] list = { 34, 72, 13, 44, 25, 30, 10 };
int[] temp = list;
Console.Write(“Original Array: “);
foreach (int i in list) {
Console.Write(i + ” “);
}
Console.WriteLine();
// reverse the array
Array.Reverse(temp);
Console.Write(“Reversed Array: “);
foreach (int i in temp) {
Console.Write(i + ” “);
}
Console.WriteLine();
//sort the array
Array.Sort(list);
Console.Write(“Sorted Array: “);
foreach (int i in list) {
Console.Write(i + ” “);
}
Console.WriteLine();
Console.ReadKey();
}
}
}
Output:
Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72
Hello! This post could not be written any better! Reading through this post reminds me of my good old room mate! He always kept talking about this. I will forward this write-up to him. Pretty sure he will have a good read. Thank you for sharing!
Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I’d prefer to use some with the content on my blog whether you don’t mind. Natually I’ll give you a link on your web blog. Thanks for sharing.