C Arrays
An array is a collection of fixed size sequential elements of same data type. An array can store multiple values. When you need to store a list of items it is easy to use an array instead of individual variable for each item. The complete set of values is referred to as an array and the individual values are called elements. An array index always starts with 0.
Declaration of an Array
The general form of array declaration is given below:
Syntax
type array_name [array_size];
If you want to declare an array named num then you have to declare the array name num as follows:
Example
int num [5];
Initialization of an Array
An array can also be initialized at the time of declaration. For example you want to represent a set of five values into an array named num. Say the values are 10, 15, 20, 25, 30.
Example
int num [5] = {10, 15, 20, 25, 30};
The values are assigned in the array as follows:
num[0] = 10;
num[1] = 15;
num[2] = 20;
num[3] = 25;
num[4] = 30;
If you want you can omit the array size. In this situation the compiler allocate enough space for all the initialized values. Therefore, you may write −
Example
int num [] = {10, 15, 20, 25, 30};
An example of a program using array:
Example:
#include <stdio.h>
int main()
{
// printf() displays the string inside quotation
int num [] = {10, 15, 20, 25, 30};
for(i=0; i<5; i++) {
printf("%d \n",num[i]);
}
return 0;
}
Output:
10 15 20 25 30