C Array

tutorial and example
tutorial and example

An array is a collection of elements that is used to hold the fixed number of values of same type.We cannot change the size and type of array after its declaration.

Why should we use Array?

We should use array because of its properties:

  • It reduces thecode while using array.
  • It is easy to traverse the data.
  • It is easy to short the element of array.
  • It is easy to access the data randomly.

There are two type of arrays in C language:

  • 1-D Array
  • 2-D Array

One Dimensional Array:

A list of items can be given one variable name using only one subscript and such a variable is called one dimensional array.

Declaration of C Array

We can declare an array by using following syntax.

Initialization of Array

There are two ways to initialize the array:

  1. First way: We can initialize the array of elements inside the bracket with comma in one line.

  1. Second way:We can initialize the array of the elements one by one. It is easy to access the elements in comparison to first way.

Example

vowel[0]=’a’;

vowel[1]=’e’;

vowel[2]=’i’;

vowel[3]=’o’;

vowel[4]=’u’;

Let us consider an example of an array;

Two Dimensional Array

Two dimensional arraysare used in the form of row and columns. It is also known as matrices

The 2D, 3D or other dimension is also known as multidimensional array.

Declaration of two dimensional arrays

The given following syntax to declare the 2D:

Syntax:

Let us consider an example:

int add[3][3];

Initialization of 2D Array in C

int  array[3][3]={{1,2,3},{2,3,4},{4,5,6}};

Example:

There are following some important points while using array:

  • We must use same data element or data at the time of initialization.
  • Array index will start with ‘0’ and end with ‘size-1’.

It uses static memory allocation at the time of working with array.