|
An array is a collection of elements of the
same data type are reference by a common name. Each element
of an array can be referred to by an array name and a
subscript or index. Arrays can be one-dimentional or two-dimentional.
Declaring One-dimentional Arrays
The general form used to declare a single-dimensional array
is:
type var-name[size];
Like other variables an array must be explicitly defined so
that the compiler can allocate memory for the array. In the
above declaration, the keyword type defines the data type of
the array, which is the data type of each element in the
array--int, float, char and size defines the number of
elements the array can hold.
An example of array declartion is:
char cArr[10];
The array subscript starts from zero. Therefore, cArr[2]
would refer to the third element in the array cArr where 2
is the array subscript.
The following program illustrates the usage of an array:
//Program 4.1
//This program performs input-output operations on arrays
#include<iostream.h>
void main()
{
int iArr[10]; //Array of size 10 is defined
int i,j;
cout<<"Input the elements of the array:"<<endl;
for(i=0; i<10; i++) //As last subscript is 9
{
cin>>iArr[i]; //i is called the array subscript
}
cout<<"The elements stored in the array are:"<<endl;
for(j=0; j<10; j++)
cout<<iArr[j]<<""; //Displays the elements of the array
}
Program 4.1 illustrates the input and output operations
using an array. Array iArr is declared to be of type int and
size 10. A maximum of 10 numbers can be stored in the array
and the individual elements are referenced using the array
subscript.
The sample output of Program 4.1 is:
Input the elements of the array:
1
2
7
9
13
16
3
8
100
21
The elements stored in the array are:
1 2 7 9 13 16 3 8 100 21
Figure 4.1 illustrates the storage of elements in the array. |