Array: Array is a collection of similar type of data in an array varaiable. Array start with Zero Index and maximum length of array is total element - 1. i.e., Suppose n is the length of array, total element in array is n-1. In memory it occupy the contiguous memory locations. The lowest address is the first element of an array and highest is the last element of an array.
A[0] | A[1] | A[2] | A[3] | A[4] | A[5] | A[6] | A[7] |
Declare an Array:
Int[] A =new int [8];
- Datatype is used to specify the type of an array.
- [] specifies the rank of an array or number of elements store in an array.
- Array_name specifies the name of an array.
- New keyword is used to allocate the memory block for an array.
Assigning value in an array:
Example 1:
Int[] A=new int[8];
A[0]=10;
A[1]=20;
Example 2:
Int[] A=new int[8]{10,20,30,40,50,60,70};
Here we declare and assign value in an array together.
Example 3:
String[] flowers=new string[]{“Lotus”,”Lilly”,”Rose”};
Here also assign value in an array but without specify the array size. In memory location it will take size of an array depend on the value we assign.
Types of Array
- Single Dimension array
- Multi Dimension Array
- Jagged Array
1. Single Dimension Array:
int[] x=new int[5];
string[] food=new string[]{“Pizza”,”Burger”,”Pasta”};
In single dimension there is only one dimension and start with 0 index.
2. Multi Dimension Array:
Multi Dimension array are 2-D array or 3-D array.
2-D array can be thought of a table or in matrix format. Which has x as number of rows and y as number of columns. Example
Int[,] B=new int[2,3];
Here 2 means number of rows and 3 stands for number of columns.
B[0][0] | B[0][1] | B[0][2] |
B[1][0] | B[1][1] | B[1][2] |
Initialize an array of 2-D
Int[,] D=new int[3,3]{{1,2,3},{4,5,6},{7,8,9}};
1 | 2 | 3 |
4 | 5 | 6 |
7 | 8 | 9 |
3. Jagged Array:
Jagged Array is an array whose elements are array. It is call array within array. The dimension and size of jagged array is different in each element.
Declaration of jagged array:
Int[][] K=new int[2][];
In the above statement 2 is number of rows in a jagged array.
Initialize value in an array:
K[0]=new int[5];
K[1]=new int[2];
K[0]-is the first element of array and now size of this array is total element-1.
K[1]-is the 2nd row of an array and total element-1.
K[0][0] | K[0][1] | K[0][1] | K[0][2] | K[0][3] |
K[1][0] | K[1][1] | K[1][2] |
|