Arrays
An array is a data structure that contains several variables of the same type. User defined reference type.
Types of arrays
1. Single Dimension 2. Multi Dimension
Creating an Array
Declaring an array Creating memory locations Putting values into memory locations
Note- The address of first index of array is stored in stack but the array is stored in heap.
Declaration of arrays
type [] arrayName Ex- int [] count; float [] marks; double [] x,y;
Creation of Arrays
arrayName =new type[size]; Ex- count=new int[5]; marks=new float[10];
Initialization
arrayName[index]= value; Ex- marks[0]=98; marks[1]=45; . . . marks[9]=60;
Other ways of array declaration
Int [] number={1,2,3,4,5}; Int[] number=new int[5]{1,2,3,4,5};
foreach loop
Read only, forward only loop Syntaxforeach(type identifier in expression) { //code here } Ex-foreach (string str in array2) { [Link](str); }
Properties and Methods
Properties Length Rank Methods GetUpperBound() GetLowerBound()
Sorting and params keyword
Sorting [Link](arrayName); params keyword It is a keyword used for creating as a parameter in our methods
Params keyword
static int add(params int[] array) { int total = 0; foreach (int i in array) { total += i; } return total;
Multi dimension Array
Arrays with more than one dimension. Syntaxint[,] array=new int[No of rows,No of cols]; Ex-int[,]arr=new int[,]{{1,2},{3,4}}; //OK int [,]array={{1,2},{3,4}}; //Ok int [, ] ar; ar ={{1,2},{3,4}}; //Error
Methods and Properties
Properties Length Rank Methods Sort Clear GetLength GetValue SetValue CreateInstance
Jagged Arrays
Array whose elements are arrays. Syntaxint[][] jaggedArray=new int[3][]; jaggedArray[0]=new int[4]; jaggedArray[1]=new int[5]; jaggedArray[2]=new int[6];
Example of jagged Array
int[][] jaggedArray = new int[3][]; jaggedArray[0] = new int[4]{1,2,3,4}; jaggedArray[1] = new int[5]; jaggedArray[1][0] = 33; jaggedArray[2] =new int[] {1,2,3,4,5,5}; foreach (int []item in jaggedArray) { foreach (int x in item) { [Link](x+" "); } [Link]( ); }