Arrays in C Language


The C language provides a capability that enables the user to define a set of ordered data items known as an array.
What is an array?
 Arrays are collection of similar items (i.e. ints, floats, chars) whose memory is allocated in a contiguous block of memory.

Declaration of arrays
Arrays must be declared before they are used like any other variable.
The general form of declaration is:

<data-type>   variable-name[SIZE];

Example: int a[10] ;

the above array can be represented as :

a:  a[0]  a[1]    a[2]     a[3]    a[4]    a[5]      a[6]    a[7]    a[8]    a[9]
 0
1
2
3
 4
5
6
7
8
9


The data type specify the type of the elements that will be contained in the array, such as int,float or char and the size indicate the maximum number of elements that can be stored inside the array.
For example, to declare an integer array which contains 100 elements we can do as follows:
int a[100];
There are some rules on array declaration.
The array name has to follow the rule of variable and the size of array has to be a positive constant integer.
We can access array elements via indexes array_name[index]. Indexes of array starts from 0 not 1 so the highest elements of an array is array_name[size-1].

Initializing Arrays:
It is like a variable, an array can be initialized. To initialize an array, we provide initializing values which are enclosed within curly braces in the declaration and placed following an equals sign after the array name.
Here is an example of initializing an integer array.
int list[5] = {2,1,3,7,8};

The following program to count the no of positive and negative numbers
/* Program to count the no of positive and negative numbers*/
#include< stdio.h >
main( )
{
int a[50],n,count_neg=0,count_pos=0,i;
printf(“Enter the size of the array\n”);
scanf(%d,&n);
printf(“Enter the elements of the array\n”);
for (i=0;i < n;i++)
scanf(%d,&a[i]);
for(i=0;i < n;i++)
{
if(a[i]< 0)
count_neg++;
else
count_pos++;
}
printf(“There are %d negative numbers in the array\n”,count_neg);
printf(“There are %d positive numbers in the array\n”,count_pos);
}

Multidimensional Arrays
An array with more than one index value is called a multidimensional array.

Often there is a need to store and manipulate two dimensional data structure such as the matrices & tables. Here array has two subscripts. One subscript denotes row & the other the column.

 To declare a multidimensional array we can do follow syntax

Syntax: <data_type> array_name[ ][ ];

Example: int m[3][3];

Here m is declared as a matrix having 3 rows (numbered from 0 to 2) and 3 columns (numbered 0 through 2). The first element of the matrix is m[0][0] and the last row last column is m[2][2].

Example:
int table[2][3]={0,0,0,1,1,1};
Initializes the elements of first row to zero and second row to 1. The initialization is done row by row. The above statement can be equivalently written as
int table[2][3]={{0,0,0},{1,1,1}}

Followers