In C language, arrays
are referred to as structured data types. An array is defined as a finite ordered collection of homogenous data, stored in contiguous memory locations.
Here the words,
- finite means data range must be defined.
- ordered means data must be stored in contiguous memory addresses.
- homogenous means data must be of a similar data type.
An example where arrays are used,
- to store the list of Employee or Student names,
- to store marks of students,
- or to store the list of numbers or characters, etc.
Since arrays provide an easy way to represent data, it is classified amongst the data structures in C. Other data structures in C are structure, lists, queues, trees, etc. The array can be used to represent not only a simple list of data but also the table of data in two or three dimensions.
Declaring an Array
Like any other variable, arrays must be declared before they are used. The general form of array declaration is,
Hereint
is the data type, arr
is the name of the array and 10 is the size of the array. It means the arrayarr
can only contain 10 elements ofint
types.
Index of an array starts from 0
to size-1 i.e first element of arr
the array will be stored at arr[0]
address and the last element will occupy arr[9]
.
Initialization of an Array
After an array is declared it must be initialized. Otherwise, it will contain a garbage value(any random value). An array can be initialized at either compile-time or at runtime.
Compile-time Array initialization
Compile-time initialization of array elements is the same as ordinary variable initialization. The general form of initialization of array is,
One important thing to remember is that when you will give more initializers (array elements) than the declared array size then the compiler will give an error.
OUTPUT: 2 3 4
Runtime Array initialization
An array can also be initialized at runtime usingscanf()
the function. This approach is usually used for initializing large arrays or to initialize arrays with user-specified values. Example,
Two-dimensional Arrays
C language supports multidimensional arrays also. The simplest form of a multidimensional array is the two-dimensional array. Both the row's and column's index begins from 0
.
Two-dimensional arrays are declared as follows,
An array can also be declared and initialized together. For example,
Note: We have not assigned any row value to our array in the above example. It means we can initialize any number of rows. But, we must always specify the number of columns, else it will give a compile-time error. Here, a 2*3
multi-dimensional matrix is created.
No comments:
Post a Comment