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.

array


Declaration of an Array

The general form of array declaration is given below:

Syntax

  1. 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

  1. 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

  1. 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

  1. int num [] = {10, 15, 20, 25, 30};


An example of a program using array:

Example:

  1. #include <stdio.h>
  2. int main()
  3. {
  4. // printf() displays the string inside quotation
  5. int num [] = {10, 15, 20, 25, 30};
  6. for(i=0; i<5; i++) {
  7. printf("%d \n",num[i]);
  8. }
  9. return 0;
  10. }

Output:

10
15
20
25
30