Declaration and initializing an array

Array are defined in much the same manner as ordinary variables, excepts that each array name must be accompanied by a size specification (i.e. the number of elements). For a one-dimensional array, the size is specified by a positive integer constant, enclosed in a square bracket. The general form of an array declaration is

data – type array – name[size];
float length [25]:   /*declares an array length containing 25 real elements.
any Subscripts 0 to 24 are valid. */
      int a [20];    /*declares an array a containing maximum of 20 integer 
values. */

Note that variable size array declarations, i.e.,

int a[n];


where n is an integer variable, are illegal in C.

it is sometimes convenient to define an array size in terms of a symbolic constant, rather than a fixed integer quantity. This makes it easier to modify a program that utilizes an array, since all references to the maximum array size can be altered by simply changing the value of the symbolic constants. For example:

#define n 20
Int [n]; is valid.


Initialization

Array can be initialized via their declaration statements. For instance,
int, j [5] = {1, 3, 5, 7, 9};

declares j to be a 5 – element integer array whose elements have the initial values j [0] =1, j [1] =3,    j [2] =5, and so on.

• declares j to be a 5 – element integer array whose elements have the initial values j [0] =1, j [1] =3, j [2] =5, and so on.
type array _name [size] = {list of values};
int num [4] = {101, 150, 175, 199};
char white_space [5] = {‘\n’,’\t,’,’\r’,’\f’};
float rectangle [3] = {4.75, 15.25, 8.0};

• Values not initialized are set to zero

int table [4] = {2,4,6}; /*4th element of array table i.e., table [3] =0*/

• When an array is initialized, the dimensional value may be omitted. The number of elements in an array will be determined by the compiler.

int x [] = {16, 60, 75, 101, 17};    /*the size of array x is 5 i.e., x [0] to x [4] */
char vowels [] = {‘a’,’e’,’I’,’o’,’u’};



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext