All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
What are Arrays?
An array is a sequence of data item of homogeneous value(same type).
Memory Representation of arrays.
int marks[5] = {51,62,43,74,55};
Here an array marks of 5 elements is created. Figure shows its memory representation.
Array Declaration
To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows.
type arrayName[array size];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement:
double balance[10];
Array Initialization
int num[6] = {4,5,3,6,34,56};
int num[] = {4,5,3,6,34,56};
float press[] = { 12.4,5.6,7.5,3.3,2};
Accessing Array Elements
int arr[5] = {12,5,6,3,4};
int x= arr[3];
int y= arr[4];
int z= arr[0]+arr[2];
printf("%d %d %d",x,y,z);
output: 3 4 18
printf("%d", arr[5]);
output: Error - Array Index Out of bound
Basic Array Program
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}