You are on page 1of 4

Arrays

Data type:
o Simple data type: variables of that type can store only one value at a time.
For example: int, float,
o Structured data type: each data item is a collection of other data items. For
example: arrays.
Array is a collection of a fixed number of components (elements) wherein all of
the components have the same data type

One-dimensional array:
Declaration syntax:

intExp represents the size of the array = number of elements in the array.
o intExp is positive integer.
Example:
intnum[5];

floatgrade[20];
doublesales[15];

Accessing array elements:


General syntax:

o indexExp is called an index


o indexExp is a nonnegative integer value
1

o Index value specifies the position of the element in the array


o The array index always starts at 0
Example:
intlist[10]; //declaring an array named list composed of 10 integer values
list[5]=34; //the 6th element of the array contains 34

list[3]=10;
list[6]=35;
list[5]=list[3]+list[6];

cout<<list[3]+list[6]<<endl;

Example:
We can declare arrays as follows:
constintarray_size=10;
intlist[array_size];

When we declare an array, its size must be known.


For example, we cannot do the following:
ints;
cin>>s;
intlist[s];

When the compiler compiles the last line, the size of the array is unknown
and the compiler will not know how much memory space to allocate for the
array.
Processing One-Dimensional Arrays
Some basic operations can be performed on a one-dimensional array such as:
Initializing
Inputting data
Outputting data stored in an array
Other operations
Each operation requires ability to step through the elements of the array
Easily accomplished by a loop
Array initialization during declaration
Arrays can be initialized during declaration. In this case, it is not necessary to
specify the size of the array.
Size determined by the number of initial values in the braces.
Example:
doublesales[]={12.25,32.50,16.90,23,45.68};
intX[]={3,2,4,5,10,1};
intX[6]={3,2,4,5,10,1};
intlist[5]={0};00000
intX[5]={1,4};14000
3

intB[];
intB[6]=X;
cin>>B;

Example:
intA[10];
//initializingthearray
for(inti=0;i<10;i++)
A[i]=5;
//Insertingvaluesofarrayelements(readingarrayvalues)
for(inti=0;i<10;i++)
cin>>A[i];
cin<<A;//illegal
//Printingvaluesofarrayelements
for(inti=0;i<10;i++)
cout<<A[i];
//otheroperations
//Findingthesumandaverageofarrayelements
intsum=0;
for(inti=0;i<10;i++)
sum+=A[i];
cout<<sum=<<sum<<;
cout<<average=<<sum/10<<endl;
//Findingthemaximumofarray(largestelement)
intmax=A[0];
for(inti=1;i<10;i++)
if(A[i]>max)max=A[i];

cout<<max=<<max<<endl;
//CopyelementsofarrayAtonewarrayC
intA[10];
intC[10];
C=A;//illegal

//CopyelementsofarrayAtonewarrayDinreverseorder

//Counttheoccurrencesof4inthearrayA

You might also like