Friday, April 28, 2017

Array Introduction and Declaration

Introduction 


Array is an index collection of fixed no. of homogeneous data element.
The main Advantage of Array is we can store huge no. of value using a single variable so that readability of the code will be improved.

But the main disadvantage of Array is fixed in size. i.e.  Once we create an array than there is no chance of increasing or decreasing the size of array as per our requirement. Hence to use an array concept we must have to know the size in advance, which is not possible always.

Array declaration

One Dimensional (1-D)Array Declaration.

int []  x;
int   []x;
int    x[];
All the above declaration  is valid but 1st one is recommended because  variable name is clearly separated from the Type.
Note: - We can not specify the size of array at the time of declaration if  we try to specify the array size than we get compile time Error (C.E)


Example :-
int []  x; valid


int [6]  x; ➜ invalid    C.E 1 :   ']' expected.
                          C.E 2 : not a statement.
                            C.E 3 : illegal start of expression.

Two Dimensional (2-D)Array Declaration.

int [][]   x;
int    [][]x;
int   x[][];
int []   x[];
int[]    []x;
int     []x[];

All the above are valid in 2-D.

Note: - if you want to specify dimension just before the variable name in array declaration it is valid only for the 1st variable in a declaration but not for onward other variable.

Int [] a, [] b   ; ➜ invalid    C.E 1 :';' expected.

Valid for variable ‘a ‘but not for’ b’ so we get compile time error.

Three Dimensional (3-D)Array Declaration.

int [][][]  x;
int      [][][]x;
int      x[][][];
int[]    [][]x;
int[]    []x[];
int[]    x[][];
int [][]    []x;
int [][]     x[];
int      []x[][];
int     [][]x[];

All are valid for 3-D.
So one you can declare multiple dimensions in multiple ways…

No comments:

Post a Comment