Lecture 2 Arrays
Lecture 2 Arrays
Affefah Qureshi
Department of Computer Science
Iqra University, Islamabad Campus.
Arrays
•An array is defined as
• Ordered collection of a fixed number of elements
• All elements are of the same data type
•Basic operations
• Direct access to each element in the array
• Values can be retrieved or stored in each element
Properties of an Array
•Ordered
• Every element has a well defined position
• First element, second element, etc.
•Fixed size or capacity
• Total number of elements are fixed
•Homogeneous
• Elements must be of the same data type (and size)
• Use arrays only for homogeneous data sets
•Direct access
• Elements are accessed directly by their position
• Time to access each element is same
• Different to sequential access where an element is only accessed after the
preceding elements
Declaring Arrays in C/C++
dataType arrayName[size];
• datatype – Any data type, e.g., integer, character, etc.
• arrayName – Name of array using any valid identifier
• intExp – Constant expression that evaluates to a positive integer
• Example:
• const int SIZE = 10; Why constant?
• Int list[SIZE];
...
• list[0] = value + 2;
list[9]
C/C++ Implementation of an Array ADT
As an ADT In C/C++
Ordered Index: 0 ,1 ,2 , … SIZE‐1
Fixed Size intExp is constant
Homogeneous dataType is the type of all elements
Direct Access Array subscripting operator [ ]
Array Initialization in C/C++
dataType arrayName[index] = {list of values}
•In C/C++, arrays can be initialized at declaration
• index is optional: Not necessary to specify the size
•Example: Numeric arrays
double score[ ] = {0.11,0.13, 0.16, 0.18, 0.21}
0 1 2 3 4
score 0.11 0.13 0.16 0.18 0.21
• Example:
• double score[5] = {0.11, 0.13, 0.16}
0 1 2 3 4
score 0.11 0.13 0.16 0 0
•Translation
• Base address + offset = 1000 + 3 x sizeof(int) = 1012
• Content of address 1012 are retrieved & displayed
• Rows and columns are numbered from 0 score [0] [1] [2] [3]
• Use nested loops to vary two indices [0] 2.7
• Row-wise or column-wise manner [1]
• Example: [2] 0.7
[3]
double value = score[2][1];
...
...
...
...
score[0][3] = value + 2.0;
[9]
Two-dimensional Arrays in
Memory
• Two ways to be represented in memory
• Column majored
• Column by column
• Row majored
• Row by row
• Representation depends upon the programming language
(1,1) (1,1)
(2,1) Column 1 (1,2) Row 1
(3,1) (1,3)
(1,2) (1,4)
(2,2) Column 2 (2,1)
(3,2) (2,2) Row 2
(1,3) (2,3)
(2,3) Column 3 (2,4)
(3,3) (3,1)
(1,4) (3,2) Row 3
(2,4) Column 4 (3,3)
(3,4) (3,4)
Any Question So Far?