C: Arrays
An array is a finite sequence of data items of the same type. For example, a sequence of all prime numbers less than 10
{2, 3, 5, 7}
is an array of type int
. A sequence of five vowels
{'a','e','i','o','u'}
is an array of type char
. A sequence of average monthly normal temperature (°C) in Shillong
{11.5, 13.1, 16.5, 18.1, 19.3, 20.3, 20.1, 20.6, 20.2, 19.3, 16.4, 12.7}
is an array of type float
. Each data item in an array is known as an element
.
Declaring an Array
To use an array in C, we first need to declare it. An array n
of 5 integers is declared as
int n[5];
The number 5 within square brackets is also known as the array's size. Similarly, an array of 10 characters is declared as
char c[10];
Array Initialization
As no specific values have been assigned to any element of the above declared arrays, they contain garbage values. Arrays may be initialized during declaration. Here we declare an array p
of type int
and initialize it with prime numbers less than 10
int p[4] = {2,3,5,7};
If an array is initialized during declaration (as above), then specifying its size is optional. The following initialization also works
int p[] = {2,3,5,7};
Accessing Array Elements
In C, subscripts/indexes of an array start at 0. An array element is accessed by writing the array name followed by its subscript/index enclosed in square brackets. So, p[0]
gives the value of the first element of the array p
, p[1]
gives the value of the second element, and p[n-1]
gives the value of the nth element. Below we print the elements of the initialized array p
int p[] = {2,3,5,7};
printf("%d \n", p[0]); //2
printf("%d \n", p[1]); //3
printf("%d \n", p[2]); //5
printf("%d \n", p[3]); //7
where \n
in the printf()
is the newline escape sequence. We can shorten the above code using the for
loop
int p[] = {2,3,5,7};
unsigned i;
for(i = 0; i < 4;i++) {
printf("%d \n", p[i]);
}
We can also assign some value to an accessed element. For example, our previous initialization of integer array p
with prime numbers less than 10 as
int p[4] = {2,3,5,7};
can also be initialized as follows
int p[4];
p[0] = 2;
p[1] = 3;
p[2] = 5;
p[3] = 7;