Topic 6 Arrays
Topic 6 Arrays
1
Array
• An array is a collection of data values.
• If your program needs to deal with 100
integers, 500 Account objects, 365 real
numbers, etc., you will use an array.
• An array is also an indexed collection of
data values of the same type.
2
Arrays of Primitive Data Types
• Array Declaration
3
Accessing Individual Elements
• Individual elements in an array accessed with the indexed
expression.
double rainfall[12];
rainfall
0 1 2 3 4 5 6 7 8 9 10 11
This
Thisindexed
indexedexpression
expression
refers
refers to the elementatat
to the element
The index of the first rainfall[2] position
position#2 #2
position in an array is 0.
4
Array Processing – Sample1
double rainfall[12];
The
Thepublic
publicconstant
constant
length
length returnsthe
returns the
double annualAverage, capacity
capacityofofan
anarray.
array.
sum = 0.0;
5
Array Initialization
• Like other data types, it is possible to
declare and initialize an array at the same
time.
int number[5] = { 2, 4, 6, 8, 10};
int measure [] = {0, 0, 0, 0};
int number[];
cout<<“Enter Size of an array”;
cin>>size
int number[size];
7
Two-Dimensional Arrays
• Two-dimensional arrays are useful in representing tabular information.
8
Declaring and Creating a 2-D Array
Declaration
Creation
double[][] payScaleTable;
0
payScaleTable 1
= new double[4][5]; 2
3
9
Accessing an Element
• An element in a two-dimensional array is
accessed by its row and column index.
10
Sample 2-D Array Processing
• Find the average of each row.
average[i] += payScaleTable[i][j];
}
11
Implementation of 2-D Arrays
• The sample array creation