Page 45 - DCAP407_DATA_STRUCTURE
P. 45
Data Structure
data, which includes string, integers, Boolean, and so on. An array can also handle other variables as
well as other arrays. An integer index identifies the individual elements of an array.
Declaring an Array
An array is declared before it is accessed. The syntax for accessing an array component is:
data-type array_name[size];
Here, data-type can be of various types like int, float, or char. The array name defines the name of the
array and size defines its element storage capacity. In C, the array index starts from 0.
Declaring an array
int a[14];
Here, 14 memory locations are reserved for the variable a where the items
have index ranging from 0-13. The array starts from the index 0, which is the
lower bound and ends at the upper bound 13. Therefore, a[4] would refer to
the fifth element in the array a, where 4 is the array index or subscript.
Name of an array without array index refers to the address of the first element.
a or a[0] refers to the first element of the array a.
Initializing an Array
We can initialize an array by assigning values to the elements during declaration. We can access the
element by specifying its index. While initializing an array, the initial values are given sequentially
separated by commas and enclosed in braces.
Consider the elements 10, 20, 30, and 40. The array can be represented as:
a[4]={10, 20, 30, 40}
The elements can be stored in an array as shown below:
a[0] = 10
a[1] = 20
a[2] = 30
a[3] = 40
The element 20 can be accessed by referencing a[1].
Now, consider n number of elements in an array. Hence, to access any element
within the array, we use a[i], where i is the value between 0 to n-1.
The corresponding code used in C language to read n number of integers in an
array is:
for(i= 0; i<n; i++)
{
scanf(“%d”,&a[i]);
}
Consider a class of 10 students whose weight is recorded as {24, 28, 26, 30, 34,
36, 42, 44, 50, 45}. The array can be represented as a[10] = {24, 28, 26, 30, 34, 36,
42, 44, 50, 45}; and the element 26 can be accessed by referencing a[2].
38 LOVELY PROFESSIONAL UNIVERSITY