Concept
Array is a data structure storing a group of elements, all of which are of the same data type.
All the elements of an array share the same name, and they are distinguished from one another with the help of an index.
Declaration
Syntax of array declaration is as follows:
data-type array_name [constant-size];
where
Data-type refers to the type of elements you want to store
Constant-size is the number of elements
Example declarations for arrays:
int charr [80];
float farr [500];
int iarr [80];
char charray [40];
There are two restrictions for using arrays in C:
- The amount of storage for a declared array has to be specified at compile time before execution. This means that an array has a fixed size.
- The data type of an array applies uniformly to all the elements; for this reason, an array is called a homogeneous data structure.
Initialisation of Array
Arrays can be initialized after their declaration.
Example1:
int nums[3]; //Declaration of Array
nums[0]=10; //initialisation array using index value
num2[1]=20;
num3[2]=30;
We can also initialise an array along with its declaration.
Example:
int digits [10] = {1,2,3,4,5,6,7,8,9,10};
int digits[ ] = {1,2,3,4,5,6,7,8,9,10};
int vector[5] = {12,-2,33,21,13};
float temperature[10] ={ 31.2, 22.3, 41.4, 33.2, 23.3, 32.3, 41.1, 10.8, 11.3, 42.3};
double width[ ] = { 17.33333456, -1.212121213, 222.191345 };
int height[ 10 ] = { 60, 70, 68, 72, 68 };
Display Array Elements
Since array elements are distinguished using their index values, we can make use of ‘for loop’ to traverse through array elements.