An array is a collection of elements of the same type stored in contiguous memory locations. An array declaration specifies the element type, array name, and number of elements.
#include <stdio.h>
int main(void)
{
int numbers[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
printf("%d\n", numbers[0]);
printf("%d\n", numbers[2]);
printf("%d\n", numbers[4]);
return 0;
}
Example Output #
10
30
50
Explanation #
The declaration:
int numbers[5];
declares an array named numbers that contains five elements of type int.
Array indexing starts at 0. Therefore, an array containing five elements has valid indices from 0 through 4.
| Element | Index | Assigned value |
|---|---|---|
numbers[0] |
0 | 10 |
numbers[1] |
1 | 20 |
numbers[2] |
2 | 30 |
numbers[3] |
3 | 40 |
numbers[4] |
4 | 50 |
An individual element is accessed using the array name followed by an index enclosed in square brackets.
numbers[2] = 30;
This statement assigns 30 to the element at index 2.
Array Declaration Syntax #
data_type array_name[array_size];
| Component | Description | Example |
|---|---|---|
data_type |
Type of each element | int |
array_name |
Identifier for the array | numbers |
array_size |
Number of elements | 5 |
Arrays can contain different element types by declaring separate arrays:
int ages[5];
float temperatures[10];
char letters[4];
double measurements[8];
For an ordinary array declaration, the size must be a valid array bound. A fixed-size array can use an integer constant expression:
#define SIZE 5
int numbers[SIZE];
The elements of a local array declared without an initializer have indeterminate values. They should be assigned valid values before those values are read.