next up previous
Next: Activity Up: Overview of C++ Previous: switch Statement

Arrays

The simplest form of arrays is the one dimensional array. The general form of the one dimensional array is


\begin{emph}
type variable\_name[size];\ \end{emph}

Here type declares the type of array. Example for an integer arrays of 10 the declaration can be written as

int sample[10];

Example
#include <iostream.h>
main()
{
int sample[10]; //reserve 10 integers elements
int t;
for(t=0;t<10; ++t) sample[t]=t; //load the array
// display the array
for(t=0;t<10; ++t) cout <<sample[t]<<' ';
return 0;
}

C++ allows multidimensional arrays. The simplest for of the multidimensional array is the two dimensional array. The general form of a two dimensional array is


\begin{emph}
type var\_name[size][size];\  \end{emph}

Example
#include <iostream.h>
main()
{
int t,i;
int num[3][4];
for(t=0;t<3;++t){
for(i=0,i<4;++i){
num[t][i]=(t*4)+i+1;
cout << num[t][i] <<' ';
}
cout <<"$\backslash$n";
}
return 0;
}
C++ allows arrays with more than two dimensions. Here is a general form of a multidimensional array declaration:

Type name[size1][size2][size3]...[sizeN]

For example, the following declaration creates a 4$\times$10$\times$3 integer array.

int multi_dimen[4][10][3];

Arrays of three or more dimensions are not often used, due to the amount of memory required to hold them. The storage for all array element is allocated during the entire lifetime of an array. When multidimensional arrays are used, large amounts of memory are consumed.


 
next up previous
Next: Activity Up: Overview of C++ Previous: switch Statement
Yousef Haik
2/23/1998