Arrays –it’s a set of similar type value that is
store sequentially. They can be arranged in three different types like –
- single dimensional
- two dimensional
- Jagged arrays.
In C# arrays
can be declared as fixed length or dynamic. Fixed length array can store a
predefined number of items while the size of dynamic array increases as you add
new items to the array.
Single
Dimensional Array – These are array which store the values in
the form of a row.
Syntax of
defining the 1 D Array -
(Type) [] (name) = new (type) [size];
int [] arr = new int [4];
or
int [] arr ;
arr = new int[5];
or
int [] arr = {list of values};
Program
using System;
class SDArray
{
static void
{
int[] arr = new int[5];
arr[0]=10;arr[1]=20;arr[2]=30;arr[3]=40;arr[4]=50;
for(int i=0;i<5;i++)
Console.Write(arr[i] + " ");
Console.WriteLine();
foreach(int i in arr)
Console.Write(i + " ");
}
}
|
foreach loop
– As discussed earlier it has been
specially designed for processing values of an array or collection for each
iteration of the loop one value of the array is assigned to the variable of the
loop and returned to us.
In case of a
for loop the variable of the loop refers to index of the array whereas in case
of the foreach loop it refers to values of the array.
In case of a
for loop the loop variable will always be in only whereas in case of a foreach
loop the loop variables type depends upon the type of values in the array.
Note – Arrays are reference type because they give us flexibility
to declare a array without specifying any size and later the size can be
specified, where this flexibility is given only to reference type.
Array Class- It is a predefined class under the system name space which
provides a set of methods and properties (variables) which can be applied on an
array.
- sort (array)
- reverse (array)
- copy (src, dest , n)
- length
Program
using System;
class SDArray2
{
static void
{
int[] arr = {34, 78, 20, 98, 72,
48, 56, 61, 70, 8, 15};
for(int i=0;i
Console.Write(arr[i] + " ");
Console.WriteLine();
Array.Sort(arr);
foreach(int i in arr)
Console.Write(i + " ");
Console.WriteLine();
Array.Reverse(arr);
foreach(int i in arr)
Console.Write(i + " ");
Console.WriteLine();
int[] brr = new int[10];
Array.Copy(arr, brr, 5);
foreach(int i in brr)
Console.Write(i + " ");
Console.WriteLine();
}
}
|
TWO
Dimensional Arrays – These are the arrays which can store values in
the form of rows and columns.
(type)[,](name) = new
(type)[rows,cols];
int[,]arr = new int[3,4];
or
int[,]arr;
arr = new int[2,3];
or
int[,] = {list of values};
|