Lecture 2 - Arrays ADT

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Data Structures

2. Arrays ADT and C++ Implementation

2-Arrays ADT 1
Abstract Data Types (1)

• A definition of data type solely in terms of


– Set of related data items (or values)
– Set of operations on the data

• Separation of logical properties from the implementation details


– Hide implementation details (Encapsulation!) User

• What not how is the focus


Interface

Implementation

1-ADTs
Operations 2
ADT vs. Data Structures

Data Type

ADT:
- Type Data Items:
Logical Form
- Operations

Data Structure:
Data Items:
- Storage Space Physical Form
- Subroutines

1-ADTs 3
Example: Airplane Flight Reservation (1)

• Consider example of an airplane flight with 10 seats to be assigned

• Operations
– List available seats
– Reserve a seat

• Implementation: How to store, access data?


– 10 individual variables

1-ADTs 4
Implementation: 10 Individual Variables
List available seats: Reserve a seat:

1. if seat1 == ‘ ’; 1. Set DONE to false


display 1 2. if seat1 ==‘ ’;
2. if seat2 == ‘ ’; print “do you want seat #1??”
display 2 Get answer
. if answer==‘Y’;
. set seat1 to ‘X’
. set Done to True
3. if seat2 ==‘ ’ and Done == false;
10. if seat10 == ‘ ’; print “do you want seat #2??”
display 10 Get answer
if answer==‘Y’;
set seat2 to ‘X’
set Done to True
.
.
.

1-ADTs 5
Example: Airplane Flight Reservation (2)

• Consider example of an airplane flight with 10 seats to be assigned

• Operations
– List available seats
– Reserve a seat

• Implementation: How to store, access data?


– 10 individual variables
– An array of variables

1-ADTs 6
Implementation: An array of variables

List available seats:


for number ranging from 0 to max_seats-1, do:
if seat[number] == ‘ ’;
Display number

Reserve a seat:
Reading number of seat to be reserved
if seat[number] is equal to ‘ ’;
set seat[number] to ‘X’
else
Display a message that the seat having this number is
occupied

1-ADTs 7
Example: Airplane Flight Reservation (2)

• This simple example illustrate the concept of an Abstract Data Type

• ADT consists of
– Collection of data items
– Basic operations that must be performed on them

• In the example, a collection of data is a list of seats

• Basic operations are


– List available seats
– Reserve a seat

1-ADTs 8
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

2-Arrays ADT 9
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

2-Arrays ADT 10
C/C++ Implementation of an Array ADT

dataType arrayName[intExp];

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 [ ]

2-Arrays ADT 11
Recap: Declaring Arrays in C/C++

dataType arrayName[intExp];

• 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: Why constant?


– const int SIZE = 10;
– int list[SIZE];

• Compiler reserves a block of consecutive memory locations enough


to hold SIZE values of type int

2-Arrays ADT 12
Recap: Accessing Arrays in C/C++

arrayName[indexExp];

• indexExp – called index, is any expression that evaluates to a


positive integer

• In C/C++
– Array index starts at 0
– Elements of array are indexed 0, 1, 2, …, SIZE-1
– [ ] is called array subscripting operator list[0] 7
list[1]
• Example list[2] 5
– int value = list[2]; list[3]

– list[0] = value + 2;

...
list[9]

2-Arrays ADT 13
Array Initialization in C/C++ (1)

dataType arrayName[intExp]= {list of values}

• In C/C++, arrays can be initialized at declaration


– intExp 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: Character arrays


– char vowel [5] = { ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ }
0 1 2 3 4
vowel A E I O U

2-Arrays ADT 14
Array Initialization in C/C++ (2)

• Fewer values are specified than the declared size of an array


– Numeric arrays: Remaining elements are assigned zero
– Character arrays: Remaining elements contains null character ‘\0’
⮚ ASCII code of ‘\0’ is zero
• Example
– double score[5] = {0.11, 0.13, 0.16}
0 1 2 3 4
score 0.11 0.13 0.16 0 0
– char name[6] = {‘J’, ‘O’, ‘H’, ‘N’}
0 1 2 3 4 5
name J O H N \0 \0

• If more values are specified than declared size of an array


– Error is occurred: Handling depends on compiler

2-Arrays ADT 15
Array Addressing (1)
• Consider an array declaration: int list [4] = { 1, 2, 4, 5}
– Compiler allocates a block of four memory spaces
– Each memory space is large enough to store an int value
– Four memory spaces are contiguous
• Base address
– Address of the first byte (or word) in the contiguous block of memory
– Address of the memory location of the first array element
⮚ Address of element list[0]
list list[0] 1000
• Memory address associated with 1001
1002
arrayName stores the base address list[1] 1003
1004
• Example 1005
1006
1007
– cout << list << endl; (Print 1000) list[2] 1008
1009
– cout << *list << endl; (Print 1) 1010
1011
• * is dereferencing operator list[3] 1012
1013
1014
– Returns content of a memory location 1015

2-Arrays ADT 16
Array Addressing (2)
• Consider a statement: cout << list[3];
– Requires array reference list[3]be translated into memory address
– Offset: Determines the address of a particular element w.r.t. base
address

• Translation
– Base address + offset = 1000 + 3 x sizeof(int) = 1012
– Content of address 1012 are retrieved & displayed
list[0] 1000
1001
• An address translation is carried out 1002
1003
each time an array element is accessed list[1] 1004
1005
1006
1007
list[2] 1008
• What will be printed and why? 1009
1010
– cout << *(list+3) << endl; 1011
list[3] 1012
1013
1014
1015
2-Arrays ADT 17
Questions

• Why does an array index start at zero?

• Why are arrays not passed by value?

2-Arrays ADT 18
Multidimensional Arrays
• Most languages support arrays with more than one dimension
– High dimensions capture characteristics/correlations associated with data

• Example: A table of test scores for different students on several tests


– 2D array is suitable for storage and processing of data

2-Arrays ADT 19
Two Dimensional Arrays – Declaration

dataType arrayName[intExp1][intExp2];

• intExp1 – constant expression specifying number of rows


• intExp2 – constant expression specifying number of columns

• Example:
– const int NUM_ROW = 2, NUM_COLUMN = 4;
– double scoreTable [NUM_ROW][NUM_COLUMN];

• Initialization:
– double scoreTable [ ][4] = { {0.5, 0.6, 0.3},
{0.6, 0.3, 0.8}};
– List the initial values in braces, row by row
– May use internal braces for each row to improve readability

2-Arrays ADT 20
Two Dimensional Arrays – Processing

arrayName[indexExp1][indexExp2];

• indexExp1 – row index


• indexExp2 – column index

• Rows and columns are numbered from 0


• Use nested loops to vary two indices
– Row-wise or column-wise manner score [0] [1] [2] [3]
[0] 2.7
[1]
• Example
[2] 0.7
– double value = score[2][1];
[3]
– score[0][3] = value + 2.0;

...
...

...

...
[9]

2-Arrays ADT 21
Array of Arrays (1)
score [0] [1] [2] [3]
• Consider the declaration
[0]
– double score[10][4];
[1]
[2]
• Another way of declaration [3]
– One-dimensional (1D) array of rows

...
...

...

...
[9]
typedef double RowOfTable[4];
RowOfTable score[10];
score [0] [1] [2] [3]
• In detail [0]
– Declare score as 1D array containing [1]
10 elements [2]
– Each of 10 elements is 1D array of 4 [3]
real numbers (i.e., double)

...

...

...

...
[9]
2-Arrays ADT 22
Array of Arrays (2)
• Score[i]
– Indicates ith row of the table

• Score[i][j]
– Can be thought of as (score[i])[j]
– Indicates jth element of score[i]

Generalization:
An n-dimensional array can be viewed (recursively) as a 1D array whose elements
are (n-1)-dimensional arrays

2-Arrays ADT 23
Array of Arrays – Address Translation
• How to access the value of score[5][3]?

• Suppose base address of score is 0x12348

• Address of 5th element of score array, i.e., score[5]


– 0x12348 + 5 x sizeof(RowOfTable) = 0x12348 + 5 x (4 x 8)
= 0x12488

• Address of score[5][3]
– Address of score[5] + 3 x sizeof(double) = 0x12488 + 3 x 8
= 0x124a0

typedef double RowOfTable[4];


RowOfTable score[10]

2-Arrays ADT 24
Higher Dimensional Arrays

• Example: Store and process a table of test scores


– For several different students
– On several different tests
– Belonging to different semesters

const int SEMS = 10, STUDENTS = 30, TESTS = 4;


typedef double ThreeDimArray[SEMS][STUDENTS][TESTS];
ThreeDimArray gradeBook;

• What is represented by gradebook[4][2][3]?


– Score of 3rd student belonging to 5th semester on 4th test

• All indices start from zero

2-Arrays ADT 25
Implementing Multidimensional Arrays

• More complicated than one dimensional arrays

• Memory is organized as a sequence of memory locations


– One-dimensional (1D) organization

• How to use a 1D organization to store multidimensional data?

• Example:
A B C D
E F G H
I J K L
– A character requires single byte
– Compiler request to reserve 12 consecutive bytes
– Two way to store consecutively, i.e., row-wise and column-wise

2-Arrays ADT 26
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

2-Arrays ADT 27
Any Question So Far?

2-Arrays ADT 28

You might also like