Top Banner
1 Data Structures and Abstract Data Types Chapter 2
40
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Lec2&3 data structure

1

Data Structures and Abstract Data Types

Chapter 2

Page 2: Lec2&3 data structure

2

Chapter Contents

1 Data Structures, Abstract Data Types and Implementations

2 Static Arrays

3 Multidimensional Arrays (optional)

4 Dynamic Arrays

5 C-Style Structs (optional)

6 Procedural Programming

Page 3: Lec2&3 data structure

3

Chapter Objectives

• Look at ADTs, implementations in detail• Introduce arrays as ADTs• See arrays implemented as C++ static arrays• (Optional) Describe multidimensional arrays• Extend pointers to use in dynamic arrays• (Optional) Show use of C++ structs to model

objects with multiple attributes• Show example of procedural programming

paradigm

Page 4: Lec2&3 data structure

4

Data Structures, Abstract Data Types, and Implementations

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

• Tasks– List available seats– Reserve a seat

• How to store, access data?– 10 individual variables– An array of variables

Page 5: Lec2&3 data structure

5

Data Structures, Abstract Data Types, and Implementations

• Implementation consists of– Storage (data) structures– Algorithms for basic operations

• Note following figure– C++ provides large collection of data types and

structures

Page 6: Lec2&3 data structure

6

C++ Data TypesC++ Data Types

structured

array struct union class

address

pointer reference

simple

integral enum

char short int long bool

floating

float double long double

Page 7: Lec2&3 data structure

Structured Data Type

7

A structured data type is a type that

– Stores a collection of individual components with one variable name

– And allows individual components to be stored and retrieved by their position within the collection

Page 8: Lec2&3 data structure

8

Arrays

• Collection of data elements– All of same type– Each accessed by specifying position

• Static array– Compiler determines how memory allocated

• Dynamic array– Allocation takes place at run time

Page 9: Lec2&3 data structure

9

Single Dimension Arrays• Syntax:

ElementType arrayName [CAPACITY];ElementType arrayName [CAPACITY] =

{ initializer_list };

• Example:int b [10];

• Elements accessed by – name and [ ] operation b[5]

Page 10: Lec2&3 data structure

10

Character Arrays• Elements of an array may be of any type

– Including characters

• Example:char name [NAME_CAPACITY] =

"John Doe";

• If array initialized shorter than specs– extra locations filled with null character

Page 11: Lec2&3 data structure

11

Subscript Operation• We have said elements

accessed by name and [ ] numList[5]

• Consider the [ ] to be an operator– The subscript operator– Performs address

translation

• Name of the array is a pointer constant– The base address

Page 12: Lec2&3 data structure

Declare variables to

store and total 3 blood pressures

12

int bp1, bp2, bp3;

int total;

40024000 4004

bp2bp1 bp3

cin >> bp1 >> bp2 >> bp3;

total = bp1 + bp2 + bp3;

Page 13: Lec2&3 data structure

What if you wanted to store and total 1000 blood pressures?

13

int bp[1000];

// Declares an array of 1000 int values

bp[0] bp[1] bp[2] . . . . bp[999]

5000 5002 5004 5006

. . . .

Page 14: Lec2&3 data structure

One-Dimensional Array Definition

14

An array is a structured collection of components (called array elements), all of the same data type, given a single name, and stored in adjacent memory locations

The individual components are accessed by using the array name together with an integral valued index in square brackets

The index indicates the position of the component within the collection

Page 15: Lec2&3 data structure

Another Example

15

• Declare an array called temps which will hold up to 5 individual float values

float temps[5]; // Declaration allocates memory

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

number of elements in the array

indexes or subscripts

Base Address

Page 16: Lec2&3 data structure

Declaration of an Array

16

• The index is also called the subscript

• In C++, the first array element always has subscript 0, the second array element has subscript 1, etc.

• The base address of an array is its beginning address in memory

SYNTAX

DataType ArrayName[ConstIntExpression];

Page 17: Lec2&3 data structure

Yet Another Example

17

• Declare an array called name which will hold up to 10 individual char values

char name[10]; // Declaration allocates memory

number of elements in the array

name[0] name[1] name[2] name[3] name[4] . . . . . name[9]

6000 6001 6002 6003 6004 6005 6006 6007 6008 6009

Base Address

Page 18: Lec2&3 data structure

Assigning Values to Individual Array Elements

18

float temps[5]; int m = 4; // Allocates memorytemps[2] = 98.6;temps[3] = 101.2;temps[0] = 99.4;temps[m] = temps[3] / 2.0;temps[1] = temps[3] - 1.2; // What value is assigned?

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

99.4 ? 98.6 101.2 50.6

Page 19: Lec2&3 data structure

What values are assigned?

19

float temps[5]; // Allocates memory int m;

for (m = 0; m < 5; m++){ temps[m] = 100.0 + m * 0.2 ;}

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

? ? ? ? ?

Page 20: Lec2&3 data structure

Now what values are printed?

20

float temps[5]; // Allocates memoryInt m; . . . . .for (m = 4; m >= 0; m--){ cout << temps[m] << endl;}

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

100.0 100.2 100.4 100.6 100.8

Page 21: Lec2&3 data structure

Variable Subscripts

21

float temps[5]; // Allocates memory

int m = 3;

. . . . . .

What is temps[m + 1] ?

What is temps[m] + 1 ?

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

100.0 100.2 100.4 100.6 100.8

Page 22: Lec2&3 data structure

A Closer Look at the Compiler

22

float temps[5]; // Allocates memory

To the compiler, the value of the identifier temps is the base address of the array

We say temps is a pointer (because its value is an address); it “points” to a memory location

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

100.0 100.2 100.4 100.6 100.8

Page 23: Lec2&3 data structure

Initializing in a Declaration

23

int ages[5] ={ 40, 13, 20, 19, 36 };

for (int m = 0; m < 5; m++)

{

cout << ages[m];}

ages[0] ages[1] ages[2] ages[3] ages[4]

6000 6002 6004 6006 6008

40 13 20 19 36

Page 24: Lec2&3 data structure

Passing Arrays as Arguments

24

• In C++, arrays are always passed by reference

• Whenever an array is passed as an argument, its base address is sent to the called function

Page 25: Lec2&3 data structure

In C++, No Aggregate Array Operations

25

• The only thing you can do with an entire array as a whole (aggregate) is to pass it as an argument to a function

• Exception: aggregate I/O is permitted for C strings (special kinds of char arrays)

Page 26: Lec2&3 data structure

Using Arrays as Arguments to Functions

26

Generally, functions that work with arrays require 2 items of information

– The beginning memory address of the array (base address)

– The number of elements to process in the array

Page 27: Lec2&3 data structure

Example with Array Parameters

27

#include <iomanip>#include <iostream>void Obtain (int[], int); // Prototypes here void FindWarmest (const int[], int , int&);void FindAverage (const int[], int , int&);void Print (const int[], int);

using namespace std;

int main ( ){ // Array to hold up to 31 temperatures int temp[31] int numDays; int average; int hottest; int m;

27

Page 28: Lec2&3 data structure

Example continued

28

cout << “How many daily temperatures? ”; cin >> numDays;

Obtain(temp, numDays); // Call passes value of numDays and address temp cout << numDays << “ temperatures“ << endl; Print (temp, numDays);

FindAverage (temp, numDays, average); FindWarmest (temp, numDays, hottest);

cout << endl << “Average was: “ << average << endl; cout << “Highest was: “ << hottest << endl; return 0;}

28

Page 29: Lec2&3 data structure

Memory Allocated for Array

29

temp[0] temp[1] temp[2] temp[3] temp[4] . . . . . temp[30]

6000

Base Address

50 65 70 62 68 . . . . . .

int temp[31];// Array to hold up to 31 temperatures

Page 30: Lec2&3 data structure

30

void Obtain ( /* out */ int temp[] , /* in */ int number )

// User enters number temperatures at keyboard

// Precondition:// number is assigned && number > 0// Postcondition:// temp[0 . . number -1] are assigned{ int m;

for (m = 0; m < number; m++) { cout << “Enter a temperature : “; cin >> temp[m]; }} 30

Page 31: Lec2&3 data structure

31

void Print ( /* in */ const int temp[], /* in */ int number )

// Prints number temperature values to screen// Precondition:// number is assigned && number > 0// temp[0 . . number -1] are assigned// Postcondition:// temp[0 . . number -1] printed 5 per line { int m; cout << “You entered: “; for (m = 0; m < number; m++) { if (m % 5 == 0) cout << endl; cout << setw(7) << temp[m]; }}

31

Page 32: Lec2&3 data structure

32

Using Arrays

• Accessing array for output– See Fig. 1

• Accessing array for input from keyboard– See Fig. 2

• Note use of arrays as parameters– Must specify number of elements of array being

used

Page 33: Lec2&3 data structure

Figure1:Array Output Function

void display(int theArray[], int numValues)

/*-----------------------------------------------------------------

Display values in an array of integers. Precondition: 0 <= numValues < capacity of theArray. Postcondition: The first numValues integers stored in theArray have been output to cout.

-------------------------------------------------------------------------*/

{

for (int i = 0; i < numValues; i++)

cout « theArray[i] « 00 " .

cout « endl;

}33

Page 34: Lec2&3 data structure

Figure 2: Array Input Function

#include <cassert> void read(IntArray theArray, int capacity, int numValues)

/*------------------------------------------------------------------------- Input values into an array of integers from the keyboard.

Preconditions: 0 <= numValues < capacity, which is the capacity of theArray. Postcondition: numValues integers entered from the

keyboard have been stored in the first NumValues positions of theArray

-------------------------------------------------------------------------/* {

assert (numValues >= 0 && numValues <= capacity); for (int i = 0; i < numValues; i++)

cin » theArray[i] ; }

34

Page 35: Lec2&3 data structure

35

#include <iostream>using namespace std;

void main(){

int Nums[4];int Sum=0;

cout<<"Enter 4 Numbers :\n";

for(int i=0;i<4;i++)cin>>Nums[i];

for(int j=0;j<4;j++)Sum+=Nums[j];

cout<<"Sum = "<<Sum<<endl;}

Page 36: Lec2&3 data structure

36

Multidimensional Arrays• Consider multiple pages of the student grade

bookconst int NUM_ROWS = 10, NUM_COLS = 5, NUM_RANKS = 10;typedef double ThreeDimArray[NUM_ROWS][NUM_COLS][NUM_RANKS];

. . .

Page 37: Lec2&3 data structure

Example on Multidimensional Arrays• #include <iostream> using namespace std;

• int main()

• {

• // A 2-Dimensional array

• double distance[2][4] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12};

• // Scan the array from the 3rd to the 7th member

• cout << "Members of the array";

• cout << "\nDistance [0][0]" << ": " << distance[0][0];

• cout << "\nDistance [0][1]" << ": " << distance[0][1];

• cout << "\nDistance [0][2]" << ": " << distance[0][2];

• cout << "\nDistance [0][3]" << ": " << distance[0][3];

• cout << "\nDistance [1][0]" << ": " << distance[1][0];

• cout << "\nDistance [1][1]" << ": " << distance[1][1];

• cout << "\nDistance [1][2]" << ": " << distance[1][2];

• cout << "\nDistance [1][3]" << ": " << distance[1][3];

• cout << endl; return 0;

• }

• This would produce: Members of the array

• Distance [0][0]: 44.14 Distance [0][1]: 720.52

• Distance [0][2]: 96.08 Distance [0][3]: 468.78

• Distance [1][0]: 6.28 Distance [1][1]: 68.04

• Distance [1][2]: 364.55 Distance [1][3]: 6234.12 37

Page 38: Lec2&3 data structure

38

Array of Array Declarations

• An array of arrays– An array whose elements are other arrays

Page 39: Lec2&3 data structure

39

Array of Array Declarations

• Each of the rows is itself a one dimensional array of values

scoresTable[2]

is the whole row numbered 2

scoresTable[2]

is the whole row numbered 2

scoresTable [1][3]scoresTable [1][3]

Page 40: Lec2&3 data structure

40

Memory Allocation in 2-Dimensional Arrays

• Elements stored in rowwise order

• Also called column major order

location [0][4] is followed in memory by location [1][0]

location [0][4] is followed in memory by location [1][0]