Arrays in C Programming

Introduction

  • An array is a collection of similar data elements.
  • They generally have the same data types.
  • Instead of declaring variables individually, arrays help to declare them all together.
  • All the elements of an array are accessed with the help of an index.
  • They have continuous memory location.

  • array
  • In the above figure you can see the elements and the index that are alloted to them.
  • We can have as many elements as we want in an array.

Definition and Declaration of arrays

  • An array is defined in the same way as variables.
  • The only difference is that of the size-specifier which tells us the size of the array.
Syntax:
data-type  array-name [array-size];

Where,
data-type - all the array elements should have the same data-type. Any valid data-type of C can be taken.
array-name - is the name of the array.
array-size - it specifies the size of the array. It tells how many elements are present in the array.

  • The square brackets will tell us that we are dealing with an array in that particular program.
  • They will use a continuous memory.
  • The size of an array is optional. If the size is specified it should be matched with the definition.
  • An array declaration cannot have the initial values.
There are two ways of declaring an array:

1.
void main()
{
     int arr[10];        // Array declaration
     ...................
     ...................
}

2.
void main()
{
     extern arr[ ];      // Array declaration
     ..................
     ..................
}

Accessing the elements of an array

An array element is accessed by using a subscript i.e. the index number is used.

Example: To show how elements are accessed
double bonus = arr[5];

  • In the above example, you can see that the 6th element will be accessed and the action will be performed on that.
  • A loop is used for accessing all the elements of an array.
  • The value of the subscript may vary and it should be an integral value or an expression that evaluates to an integral value.
Example: Setting each element of the array to 2
int i, arr[10];
for (i=0; i<10; i++)
arr[i] = 2;


  • All the elements of the array will be set to 2.
  • Due to the for loop first value of arr[0] is set to 2 and it will keep on going till arr[9].

Initialization of arrays

The elements in an array can be initialized when they are declared.  

Syntax:
data-type array-name[array-size] = {list of values};

  • The elements of the array are not initialized by default.
  • It contains garbage value, so before the array is used it must be initialized or should read some meaningful data in it.
array initialisation