Often, we have to deal with groups of objects of same type such as names of persons, instrument readings in an experiment, roll numbers of students, and so on. These groups can be conveniently represented as elements of arrays. An array is defined as a sequence of objects of the same data type. All the elements of an array are either of type int (whole numbers), or all of them are of type char, or all of them are of floating decimal point type, etc.
An array cannot have a mixture of different data types as its elements. Also, array elements cannot be functions; however, they may be pointers to functions. In computer memory, array elements are stored in a sequence of adjacent memory blocks. Since all the elements of an array are of same data type, the memory blocks allocated to elements of an array are also of same size. Each element of an array occupies one block of memory. The size of memory blocks allocated depends on the data type and it is same as for different data types.
The declaration of array includes the type of array that is the type of value we are going to store in it, the array name and maximum number of elements.
Examples:
short val[200]; val[12] = 5;
Declaration & Data Types
Arrays have the same data types as variables, i.e., short, long, float etc. They are similar to variables: they can either be declared global or local. They are declared by the given syntax:
Datatype array_name [dimensions] = {element1,element2,….,element}
The declaration form of one-dimensional array is
Data_type array_name [size];
The following declares an array called ‘numbers’ to hold 5 integers and sets the first and last elements. C arrays are always indexed from 0. So the first integer in ‘numbers’ array is numbers[0] and the last is numbers[4].
int numbers [5]; numbers [0] = 1; // set first element numbers [4] = 5;
This array contains 5 elements. Any one of these elements may be referred to by giving the name of the array followed by the position number of the particular element in square brackets ([ ]). The first element in every array is the zeroth element. Thus, the first element of array ‘numbers’ is referred to as numbers[ 0 ], the second element of array ‘numbers’ is referred to as numbers[ 1 ], the fifth element of array ‘numbers’ is referred to as numbers[ 4 ], and, in general, the nth element of array ‘numbers’ is referred to as numbers[ n – 1 ].
Example:
#include <stdio.h> #include <conio.h> int main( ) { char name[7]; /* define a string of characters */ name[0] = 'D'; name[1] = 'I'; name[2] = 'N'; name[3] = 'E'; name[4] = 'S'; name[5] = 'H'; name[6] = '\0'; /* Null character - end of text */ name[7] = 'T'; clrscr(); printf("My name is %s\n",name); printf("First letter is %c\n",name[0]); printf("Fifth letter is %c\n",name[4]); printf("Sixth letter is %c\n",name[5]); printf("Seventh letter is %c\n",name[6]); printf("Eight letter is %c\n",name[7]); getch(); return 0; }