csi 1340 introduction to computer science ii

114
CSI 1340 Introduction to Computer Science II Chapter 2 Data Design and Implementation

Upload: aleda

Post on 04-Jan-2016

52 views

Category:

Documents


2 download

DESCRIPTION

CSI 1340 Introduction to Computer Science II. Chapter 2 Data Design and Implementation. Computers. Computers are dumb All boils down to simple operations on 0s and 1s Forest vs. Trees Not suitable for human consumption. Abstraction. Need some higher level view of computation Abstraction - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CSI 1340 Introduction to Computer Science II

CSI 1340Introduction to Computer Science II

Chapter 2Data Design and Implementation

Page 2: CSI 1340 Introduction to Computer Science II

Computers

Computers are dumb

All boils down to simple operations on 0s and 1s

Forest vs. Trees

Not suitable for human consumption

Page 3: CSI 1340 Introduction to Computer Science II

Abstraction

Need some higher level view of computation

AbstractionComposing primitives to view as a single object

Primitive data typesBit groupings and logical operations

Functions/MethodsLogical units of operations

Page 4: CSI 1340 Introduction to Computer Science II

How do we provide abstraction for data?

Primitive data types (e.g., int, char, float, double)

Encapsulation: separation of physical representation from logical use

Data Abstraction

APPLICATION

0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1

REPRESENTATION

int y;

y = 25;

Page 5: CSI 1340 Introduction to Computer Science II

Record

Next level of data abstractionComposing groupings of primitive data typesRecord: collection of related data items of different types

struct TypeName

{

DataType MemberName;

. . .

} ;

TypeName variablename;

Page 6: CSI 1340 Introduction to Computer Science II

Struct Example

typedef int IDType;struct StudentRec{

IDType studentID; float gpa;

} fred; // Declare variable like this StudentRec jane; // or this

Page 7: CSI 1340 Introduction to Computer Science II

The member selection operator (period . ) is used between the variable name and the member identifier to access individual members of a record type variable.

EXAMPLESfred.studentIDfred.gpa

Struct Member Access

Page 8: CSI 1340 Introduction to Computer Science II

Self-Test

A part in an inventory is represented by its part number (integer), a descriptive name (20 characters), the quantity on hand (integer), and the price (float). Declare a variable, called part, that is a struct.

Page 9: CSI 1340 Introduction to Computer Science II

Self-Test Answer

typedef char StringType[21];struct PartType{

int number;StringType name;int quantity;float price;

} ;PartType part;

Page 10: CSI 1340 Introduction to Computer Science II

Initializing a Struct Variable

PartType part;part.name “nail”;part.number = 145;part.quantity = 4000;part.price = 2.98;

OR

PartType part = { 145, “nail”, 4000, 2.98 };

Page 11: CSI 1340 Introduction to Computer Science II

Aggregate Struct Assignment

PartType oldPart = { 145, “nail”, 4000, 2.98 } ;PartType newPart;newPart = oldPart; // Aggregate assignment

Page 12: CSI 1340 Introduction to Computer Science II

Memory is like a shelf of slots

Referencing Memory

Each slot has a number and some content value

2

slot # 522 523 524 525

content

Page 13: CSI 1340 Introduction to Computer Science II

Referencing Memory

You can refer to a shelf slot in one of two ways:

“My shelf slot contains the number 2”

By value“My shelf slot

is number 523”

By reference

Page 14: CSI 1340 Introduction to Computer Science II

By Reference

By reference tells you where the original content livesYou can directly access the shelf slot using the slot

number to change the content

“My shelf slot is

number 523”

Page 15: CSI 1340 Introduction to Computer Science II

By Value

By value only gives you a copy of the value of the slot contents

You can change your copy of the slot contentsThis does not change the actual slot contents

“My shelf slot contains the number 2”

Page 16: CSI 1340 Introduction to Computer Science II

Pass-by-value

CALLINGBLOCK

FUNCTION CALLED

sends a copy of the contents of the actual parameter

the actual parameter cannot be changed by the function.

Page 17: CSI 1340 Introduction to Computer Science II

Pass-by-reference

sends the location (memory address)of the actual parameter

can change value ofactual parameter

CALLINGBLOCK FUNCTION

CALLED

Page 18: CSI 1340 Introduction to Computer Science II

Struct Pass by Reference

void AdjustForInflation(PartType& part, float percent)

// Increases price by the amount specified in percent{

part.price = part.price * percent + part.price;

} ;

SAMPLE CALL

AdjustForInflation(myPart, 0.03);

Page 19: CSI 1340 Introduction to Computer Science II

Struct Pass by Value

bool SufficientQuantity(PartType part, int partsNeeded)

// Returns true if the quantity of parts available meets or// exceeds the needed number of parts{

return ( part.quantity >= partsNeeded ) ;

} ;

SAMPLE CALL

if ( SufficientQuantity(myPart, 200) )cout << “Total Price: ” << myPart.price * 200 << endl ;

Page 20: CSI 1340 Introduction to Computer Science II

Aggregate Parameter Passing

void myFunc (PartType part ) // Value parameter{

. . .}void myFunc (PartType& part ) // Reference parameter{

. . .}

Page 21: CSI 1340 Introduction to Computer Science II

Aggregate Return

PartType initializePart ( ){

PartType part = {145, “nail”, 4000, 2.98};return part; // Aggregate return

}

Page 22: CSI 1340 Introduction to Computer Science II

Rules for Records

Need separate statement for each member:• Read/write values for all members.• Perform arithmetic on all the members in a record.• Compare two records.

Can use a single statement:• Assign values to all members in declaration.

Parameter passing - Value or reference allowed.Returning from value-returning function - Allowed.

Page 23: CSI 1340 Introduction to Computer Science II

Aggregate OperationI/O NoAssignment YesArithmetic NoComparison NoParameter passage Ref. or ValueReturn as fcn’s return value Yes

Struct Aggregate Operations

Page 24: CSI 1340 Introduction to Computer Science II

CSI 1340Introduction to Computer Science II

One-Dimensional Arrays

Page 25: CSI 1340 Introduction to Computer Science II

One-Dimensional Array

Collection of related items of the same type that are stored sequentially in memory and are accessed using the same name.

3 1 13 32 4 11 7 9

Page 26: CSI 1340 Introduction to Computer Science II

Declaring One-Dimensional Arrays

Must indicate the data type, array name, and maximum size of the array in the declaration

type variable[repetitions];Example:

int num[10];The repetition declaration must be of a constant,

integer type

noStudents = 5;int class[noStudents]; // Error

Page 27: CSI 1340 Introduction to Computer Science II

Accessing Array Components

Examplenum[0]. . .num[9]

The value enclosed in square brackets is called the index. The range of index values is 0 through N-1

The index variable must be of an integer type (char, short, int, long, or enum)

Page 28: CSI 1340 Introduction to Computer Science II

Out-of-Bounds Array Access

DANGER!!!!What output do you expect?

int one[5], two[3];

two[0] = 5;one[5] = 9; // Out of

bounds

cout << two[0] << endl;Output: 9 (On CodeWarrior)

Page 29: CSI 1340 Introduction to Computer Science II

Declare arrays for each of the following:– A numeric array called FArray capable of storing 24

floating point numbers

– A character array called LastName capable of storing a person’s last name (the name can be up to 15 characters in length)

– A numeric array called IArray capable of storing up to 500 integer numbers

Self-Test

float FArray[24];

char LastName[16]; // must reserve a space for ‘\0’

int IArray[500];

Page 30: CSI 1340 Introduction to Computer Science II

Array Restrictions

All of the array items must be the same type (e.g., char, short, int, long, enum)

Must declare the maximum size of the array in the array declaration (it must be as big as it will ever need to get)

Page 31: CSI 1340 Introduction to Computer Science II

Using Arrays

Assigning valuesReading valuesWriting valuesCopying arrays

Page 32: CSI 1340 Introduction to Computer Science II

Assigning Values to Arrays

Declarationint squares[3] = {0, 1, 4};int cubes[ ] = {0, 1, 8, 27};

Within a loopint squares[30];for (i=0; i < 30; i++)

squares[i] = i * i;

Page 33: CSI 1340 Introduction to Computer Science II

Reading Values for Arrays

Numeric values are read for arrays using the extraction operator in a loop.

int num[5];

for (i=0; i < 5; i++){

cout << “Enter an integer”cin >> num[i];

}

Page 34: CSI 1340 Introduction to Computer Science II

Writing Values for Arrays

Numeric arrays are written using the insertion operator in a loop.

int num[5];for (i=0; i < 5; i++)

cout << num[i];

Page 35: CSI 1340 Introduction to Computer Science II

Aggregate Operation

An operation on a data structure as a whole.C++ does NOT allow aggregate copy, comparison,

or return operations on arrays.

Page 36: CSI 1340 Introduction to Computer Science II

Aggregate copyx = y; // Not allowedfor (i = 0; i <= 9; i++) // Correct

x[i] = y[i];Aggregate comparison of arrays

if (x = = y) // Not allowedfor (i = 0; i <= 9; i++) // Correctif (x[i] = = y[i]). . .

Aggregate Operations NOT Allowed

Page 37: CSI 1340 Introduction to Computer Science II

Aggregate Operations NOT Allowed

Aggregate return.int x[5];

…return x; // Not allowed// Must pass an array as a parameter

Page 38: CSI 1340 Introduction to Computer Science II

Array Parameters

Arrays are ALWAYS passed as reference parameters (but NEVER USE &).

Address of the first element in the array (base address) is passed.

Size of the array is NOT included between the brackets in the formal parameter list. The size MUST be included as a separate parameter.

Page 39: CSI 1340 Introduction to Computer Science II

Array Example

void ZeroOut (float[ ], int); // Prototypefloat num[10]; // DeclarationZeroOut (num, 10); // Callvoid ZeroOut (float arr[ ], int nElements) // Function{

for (int i = 0; i < nElements; i++)arr[i] = 0.0;

}

Page 40: CSI 1340 Introduction to Computer Science II

Preventing Changes to An Array

Add const in the formal parameter list.bool CheckZero(const float num[ ], int nElements){

num[3] = 2; // ILLEGAL!for (int i = 0; i < nElements; i++){

if (num[i] != 0) {

return false;}

}return true;

}

Page 41: CSI 1340 Introduction to Computer Science II

Semantic Indices

You may want indices with “meaning” instead of just referring to position

enum {January, February, March};int monthDays[ ] = {31, 28, 31};

cout << "Days in March: " << monthDays[March];

Page 42: CSI 1340 Introduction to Computer Science II

Parallel Arrays

Represent list of student IDs with their grades

int ID[20];char grade[20];

ID[0] = 123456789;grade[0] = ‘B’;ID[1] = 987654321;grade[1] = ‘A’;

Page 43: CSI 1340 Introduction to Computer Science II

Rules for Arrays

Loop needed:• Read/write values for entire array.• Assign values to entire array.• Perform arithmetic on entire array.• Compare two arrays.

Parameter passing - Reference parameter only (No &).Returning from value-returning function - Not allowed.

Page 44: CSI 1340 Introduction to Computer Science II

CSI 1340Introduction to Computer Science II

Multidimensional Arrays

Page 45: CSI 1340 Introduction to Computer Science II

Two-Dimensional Arrays

Table of columns and rows

Page 46: CSI 1340 Introduction to Computer Science II

Two-Dimensional Array Declaration

Declaration:int grades[2] [4];

Alternative:const int NUM_STUDENTS = 2;const int EXAMS = 4;int grades[NUM_STUDENTS][EXAMS];

Repetitions in declaration must be a constant!!int x = 5;

const int y = 6;int grid[x][x]; // Errorint matrix[y][y]; // Works

Page 47: CSI 1340 Introduction to Computer Science II

Accessing a 2D Array

Names of the array elements are:array[row][col];

Example: grades[0][1];

Example Interpretations:• Grade 1st row, 2nd column

or• Grade 2nd grade of 1st student

(assuming students are in rows)

Page 48: CSI 1340 Introduction to Computer Science II

Initializing a 2D Array

Examplefor (row = 0; row < 2; row++)

for (col = 0; col < 4; col++)grades[row][col] = 0;

Page 49: CSI 1340 Introduction to Computer Science II

Reading a 2D Array by Row

Assume that the array is the following8 3 4 59 1 2 7

for (row = 0; row < NUM_STUDENTS; row++)for (col = 0; col < EXAMS; col++)

cin >> myArray[row] [col];

NOTE: This reads BY ROW (User must enter: 8, 3, 4, 5, 9. . .)

Page 50: CSI 1340 Introduction to Computer Science II

Reading a 2D Array by Column

Example8 3 4 59 1 2 7

for (col = 0; col < 4; col++)for (row = 0; row < 2; row++)

cin >> myArray[row] [col];

NOTE: This reads BY COLUMN (User must enter: 8, 9, 3, 1. .)

Page 51: CSI 1340 Introduction to Computer Science II

Writing a 2D Array by Row

Examplefor (row = 0; row < 2; row++) 8 3 4 5{ 9 1

2 7for (col = 0; col < 4; col++)

cout << myArray[row] [col] << ‘ ‘;cout << endl;

}NOTE: This writes BY ROW

Page 52: CSI 1340 Introduction to Computer Science II

Writing a 2D Array by Column

Examplefor (col = 0; col < 4; col++) 8 9{ 3 1

for (row = 0; row < 2; row++) 4 2cin >> myArray[row] [col]; 5 7

cout << endl;}NOTE: This writes BY COLUMN

Page 53: CSI 1340 Introduction to Computer Science II

2D Array Parameters

Only by referenceNumber of ROWS of the array is NOT included

between the brackets in the formal parameter list but the number of columns MUST be included between the second set of brackets.

Page 54: CSI 1340 Introduction to Computer Science II

2D Parameter Passing

void printArr(int a[ ][2], int rows){

for (int i=0; i < rows; i++){

for (int j=0; j < 2; j++)cout << a[i][j] << " ";

cout << endl;}

}int z[2][2] = {{1,2},{3,4}}; // Legalint z[ ][2] = {{1,2},{3,4}}; // Also legalint z[2][ ] = {{1,2},{3,4}}; // NOT legal!! printArr(z, 2);

Page 55: CSI 1340 Introduction to Computer Science II

Multi-D Arrays

There is no limit on the number of dimensionsGrade example

semesters: grades[semester][student][exam]Initialization

int z[2][2][2] = {{{11,12},{21,22}},{{31,32},{41,42}}};Parameter passing

void printArr(int a[ ][2][2], int noX)

Page 56: CSI 1340 Introduction to Computer Science II

Program #1Document.dat

1 1 1 1 1 1 1 10 0 0 0 0 0 1 00 0 0 0 0 1 0 00 0 0 0 1 0 0 00 0 0 1 0 0 0 00 0 1 0 0 0 0 00 1 0 0 0 0 0 01 1 1 1 1 1 1 10 0 0 1 1 0 0 00 0 0 1 1 0 0 00 0 0 0 0 0 0 00 0 0 1 1 0 0 00 0 0 1 1 0 0 00 0 0 1 1 0 0 00 0 0 1 1 0 0 00 0 0 1 1 0 0 0

Dictionary.dat

1 1 1 1 1 1 1 10 1 0 0 0 0 0 00 0 1 0 0 0 0 00 0 0 1 0 0 0 00 0 0 0 1 0 0 00 0 0 0 0 1 0 00 0 0 0 0 0 1 01 1 1 1 1 1 1 10 0 0 1 1 0 0 00 0 0 1 1 0 0 00 0 0 1 1 0 0 00 0 0 1 1 0 0 00 0 0 1 1 0 0 00 0 0 1 1 0 0 00 0 0 1 1 0 0 00 0 0 1 1 0 0 0

Page 57: CSI 1340 Introduction to Computer Science II

Problem 1

Declare an array named quiz that contains 12 floats indexed by the integers 0 through 11.

float quiz[12];

Page 58: CSI 1340 Introduction to Computer Science II

Problem 2

If an array is to hold the number of correct answers given by students to each question on a 20-question true/false quiz, what data type should be used for the components of the array?

boolint or short

Page 59: CSI 1340 Introduction to Computer Science II

Problem 3

Given the declarationsconst int MAX_LENGTH = 30;char firstName[MAX_LENGTH];

write an assignment statement that stores ‘A’ into the first component of array firstName

firstName[0] = ‘A’;

Page 60: CSI 1340 Introduction to Computer Science II

Problem 4

Given the declarationconst int MAX_LENGTH = 30;char firstName[MAX_LENGTH];

write an output statement that prints the value of the fourteenth component of array firstName

cout << firstName[13];

Page 61: CSI 1340 Introduction to Computer Science II

Problem 5

Declare a five-element int array named oddNums and initialize it (in its declaration) to contain the first five odd integers, starting with 1

int oddNums[5] = {1, 3, 5, 7, 9}; or

int oddNums[ ] = {1, 3, 5, 7, 9};

Page 62: CSI 1340 Introduction to Computer Science II

Give the function heading for a void function named SomeFunc, where

• SomeFunc has a single parameter:a float array x that is an Inout parameter

• SomeFunc has a single parameter:a float array x that is an In parameter

Problem 6

void SomeFunc(float x[ ])

void SomeFunc(const float x[ ])

Page 63: CSI 1340 Introduction to Computer Science II

Problem 7

Given the declarationsconst int MAX_LENGTH = 30;char firstName[MAX_LENGTH];

and the following program fragment, which reads characters into array firstName until a blank is encountered, write the statement(s) to properly print out the array

Page 64: CSI 1340 Introduction to Computer Science II

Problem 7 char firstName[MAX_LENGTH];int length = 0;char letter;do{

cin.get(letter);if (letter != ‘ ‘){

firstName[length] = letter;length++;

}} while (letter != ‘ ‘);

Page 65: CSI 1340 Introduction to Computer Science II

Problem 8

Declare two parallel arrays indexed by the integers 0 through 99. One of the arrays will contain student ID numbers (type long), the other will contain a gender code

long number[100];char gender[100];

Page 66: CSI 1340 Introduction to Computer Science II

Strings

Page 67: CSI 1340 Introduction to Computer Science II

Assigning Values to String Arrays

String values can be assigned to arrays in the array declaration or individually using assignment statements.

char name[21] = “John Doe”; // String termination (‘\0’) implicit

orname[0] = ‘J’;name[1] = ‘o’; . . .name[8] = ‘\0’; // Needed for cout to work

orchar name[ ] = {‘J’,‘o’,‘h’,‘n’,‘ ’,‘D’,‘o’,‘e’,‘\0’}; // ‘\0’ needed for cout

Page 68: CSI 1340 Introduction to Computer Science II

Danger of Nontermination

What output do you expect?char name[ ] = "XXXXX"; cout << name << endl;

name[0] = 'J'; name[1] = 'o'; name[2] = 'e';

cout << name << endl;

Output: XXXXXJoeXX

Page 69: CSI 1340 Introduction to Computer Science II

String Termination

What output do you expect?

char name[5] = "XXXXX"; // Termination implicitcout << name << endl;

Output: XXXXXΘ@

Page 70: CSI 1340 Introduction to Computer Science II

Reading Values for String Arrays

Strings can be read into arrays using the extraction operator (stops at first white space)

cin >> name;or using the get function without using a loop.

cin.get(name, 21);cin.ignore(80, ‘\n’);

Page 71: CSI 1340 Introduction to Computer Science II

Writing Values for String Arrays

String arrays can be written using the insertion operator without using a loop.

char name[21];cout << name;

Page 72: CSI 1340 Introduction to Computer Science II

Rules for String Arrays

Loop NOT needed:Read/write values for entire array

Everything else is the same as for numeric arrays

Page 73: CSI 1340 Introduction to Computer Science II

Aggregate Operations

C++ is more permissive with structs than with arrays

Aggregate Operation Arrays Structs

I/O No (exc. strings) NoAssignment No YesArithmetic No NoComparison No NoParameter passage Ref. only Ref. or ValueReturn as fcn’s return value No Yes

Page 74: CSI 1340 Introduction to Computer Science II

Array of Records

Page 75: CSI 1340 Introduction to Computer Science II

Array of Records Declaration

struct TypeName

{ DataType MemberName;

. . .} ;TypeName variablename[MAXSIZE];

Page 76: CSI 1340 Introduction to Computer Science II

Array of Records Example

const int NOSTUDS = 10;struct StudentRec{

char firstName[16]; // firstName has 15 characterschar lastName[16]; // lastName has 15 charactersfloat gpa;

} ;StudentRec student[NOSTUDS];

Page 77: CSI 1340 Introduction to Computer Science II

Array of Records Access

Accessed using a member selectorvariable[index].member

*where variable is the struct array name, index is the location in the array, and member is the member name

Examplestudent[0].firstNamestudent[0].lastNamestudent[0].gpa

Page 78: CSI 1340 Introduction to Computer Science II

Array of Records Access

How would you access the GPA of the third student?

student[2].gpa;

How would you access the first character in the last name of the second student?

student[1].lastName[0];

Page 79: CSI 1340 Introduction to Computer Science II

I/O with an Array of Records

cin.get (student[0].firstName,16);cin.get (student[0].lastName, 16);cin >> student[0].gpa;

Page 80: CSI 1340 Introduction to Computer Science II

Self-Test

An employee is represented by his/her name (30 characters), ID (11 characters), and salary (float). Define a struct, called EmployeeType, and declare a variable called employee that is an array of 25 records of EmployeeType.

Page 81: CSI 1340 Introduction to Computer Science II

Self-Test Answer

struct EmployeeType{

char name[31];char ID[12];float salary;

} ;EmployeeType employee[25];

Page 82: CSI 1340 Introduction to Computer Science II

Recall memory is like a shelf of slotsSome items need more than one slotA short variable actually takes up two memory slots

Referencing Memory

slot # 522 523 524 525

000000000000002

Page 83: CSI 1340 Introduction to Computer Science II

1 slot = 1 byte of memoryEach byte of memory has an address (slot #)Variables only identify the base address (1st slot #)

Referencing Memory

slot # 522 523 524 525

000000000000002

How do we access array data using only the base

address?

Page 84: CSI 1340 Introduction to Computer Science II

Array Access

char name[10]; // assume element size is 1 byte

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

6000 6001 6002 6003 6004 6005 6006 6007 6008 6009

Base Address

This ACCESSING FUNCTION gives position of name[Index]

Address(Index) = BaseAddress + (Index * SizeOfElement)

Page 85: CSI 1340 Introduction to Computer Science II

Array Access

float values[5]; // assume element size is 4 bytes

This ACCESSING FUNCTION gives position of values[Index]

Address(Index) = BaseAddress + (Index * SizeOfElement)

Base Address

values[0] values[1] values[2] values[3] values[4]

7000 7004 7008 7012 7016

Indices

Page 86: CSI 1340 Introduction to Computer Science II

2D Array Access

If memory is like a long shelf with slots…

How do we create and access two dimensional arrays?

Page 87: CSI 1340 Introduction to Computer Science II

In memory, C++ stores arrays in row order. The first row is followed by the second row, etc.

int grades[5][12]; (5 students/12 exams)

8000 8048 8096

Base Address

. . .

2D Array Access

12 exams forstudent 0 first row

12 exams forstudent 1

second row

Page 88: CSI 1340 Introduction to Computer Science II

2D Array Accessgrades[ 0 ] [ 0 ]grades[ 0 ] [ 1 ]grades[ 0 ] [ 2 ]grades[ 0 ] [ 3 ]grades[ 0 ] [ 4 ]grades[ 0 ] [ 5 ]grades[ 0 ] [ 6 ]grades[ 0 ] [ 7 ]grades[ 0 ] [ 8 ]grades[ 0 ] [ 9 ]grades[ 0 ] [10 ]grades[ 0 ] [11 ]grades[ 1 ] [ 0 ]grades[ 1 ] [ 1 ]grades[ 1 ] [ 2 ]grades[ 1 ] [ 3 ] . . .

To locate an element such asgrades [2] [7] the compiler needs to know that there are 12 columnsin this two-dimensional array.

At what address will grades [2] [7] be found?

Assume 4 bytes for type int.

Base Address 8000

Page 89: CSI 1340 Introduction to Computer Science II

How do we extend it2DAddress =

RowBaseAddress+

(ColumnIndex * SizeOfElement)

2D Array Accessgrades[ 0 ] [ 0 ]grades[ 0 ] [ 1 ]grades[ 0 ] [ 2 ]grades[ 0 ] [ 3 ]grades[ 0 ] [ 4 ]grades[ 0 ] [ 5 ]grades[ 0 ] [ 6 ]grades[ 0 ] [ 7 ]grades[ 0 ] [ 8 ]grades[ 0 ] [ 9 ]grades[ 0 ] [10 ]grades[ 0 ] [11 ]grades[ 1 ] [ 0 ]grades[ 1 ] [ 1 ]grades[ 1 ] [ 2 ]grades[ 1 ] [ 3 ] . . .

1D array access formulaAddress =

BaseAddress + (Index * SizeOfElement)

Base Address 8000

RowBaseAddress =

BaseAddress + (ColumnsPerRow *

RowIndex * SizeOfElement)

Page 90: CSI 1340 Introduction to Computer Science II

ND Array Parameter Passing

Array Memory Location2DAddress = ColumnBaseAddress+ (ColumnIndex * SizeOfElement)

ColumnBaseAddress = BaseAddress + (ColumnsPerRow * RowIndex * SizeOfElement)

We do not need the number of rows in this equationParameter type definition

void printArray(int a[ ], int rows);void printArray(int a[ ][2], int rows);void printArray(int a[ ][2][2], int rows);

Page 91: CSI 1340 Introduction to Computer Science II

CSI 1340Introduction to Computer Science II

Introduction to Classes

Page 92: CSI 1340 Introduction to Computer Science II

Abstraction++

struct DateType{

int year ; int month ; int day ;

} ;

void SetDate(DataType& date);void Tomorrow(DataType date);bool LaterDate(DataType date1, DataType data2);

Let’s treat it all like an object

Page 93: CSI 1340 Introduction to Computer Science II

Syntax for C++ Classes

class className

{

public:

// interface for public consumption

private:

// for className’s eyes only

};

Page 94: CSI 1340 Introduction to Computer Science II

class DateType Specification

// SPECIFICATION FILE ( datetype.h )

class DateType // declares a class data type{

public : // 4 public member functions

void Initialize ( int newMonth , int newDay , int newYear ) ;int YearIs( ) const ; // returns yearint MonthIs( ) const ; // returns monthint DayIs( ) const ; // returns day

private : // 3 private data members

int year ; int month ; int day ;

} ;

Page 95: CSI 1340 Introduction to Computer Science II

Client Code Using DateType

#include “datetype.h” // includes specification of the classusing namespace std;

int main ( void ){

DateType bobsBDay ; // declares 2 objects of DateTypeDateType janesBDay;

bobsBDay.Initialize ( 6, 30, 1998 ) ;janesBDay.Initialize( 10, 31, 2002);

cout << bobsBDay.MonthIs( ) << “/” << bobsBDay.DayIs( ) << “/” << bobsBDay.YearIs( ) << endl;}

Page 96: CSI 1340 Introduction to Computer Science II

DateType Class Instance

Initialize

YearIs

MonthIs

DayIs

bobsBDay janesBDay

Private data:

year

month

day

2002

10

31

Initialize

YearIs

MonthIs

DayIs

1998

6

30

Private data:

year

month

day

Page 97: CSI 1340 Introduction to Computer Science II

Specification and Implementation Files

Bob SmithPlumber

clogged drains, broken pipes, water heaters,leaks, floods, tubs, toilets, and sinks, oh my!

Specification

Bob

Implementation

Brain

Page 98: CSI 1340 Introduction to Computer Science II

Specification and Implementation Files

// SPECIFICATION FILE ( datetype .h ) // Specifies the data and function members. class DateType { public: . . .

private: . . . } ;

// IMPLEMENTATION FILE ( datetype.cpp ) // Implements the DateType member functions. . . .

Page 99: CSI 1340 Introduction to Computer Science II

Member Function Implementation // IMPLEMENTATION FILE (datetype.cpp)#include “datetype.h” // also must appear in client code

void DateType :: Initialize ( int newMonth, int newDay, int newYear )// Post: year is set to newYear.// month is set to newMonth.// day is set to newDay.{

year = newYear ; month = newMonth ; day = newDay ;}

Page 100: CSI 1340 Introduction to Computer Science II

int DateType :: MonthIs ( ) const

// Accessor function for data member month

{

return month ;

}

int DateType :: YearIs ( ) const

// Accessor function for data member year

{

return year ;

}

int DateType :: DayIs ( ) const

// Accessor function for data member day

{

return day ;

}

Page 101: CSI 1340 Introduction to Computer Science II

Scope Resolution Operator ( :: )

C++ programs typically use several class types.

Different classes can have member functions with the same identifer, like Write( ).

Member selection operator is used to determine the class whose member function Write( ) is invoked.

currentDate .Write( ) ; // class DateTypenumberZ .Write( ) ; // class ComplexNumberType

In the implementation file, the scope resolution operator is used in the heading before the member function’s name to specify its class.

void DateType :: Write ( ) const{ . . .

}

Page 102: CSI 1340 Introduction to Computer Science II

C++ Header File - table.h

// Documentation that describes the classclass Table {public:

void ReadByRows(int rows, int cols);void ReadByCols(int rows, int cols);void WriteByRows(int rows, int cols) const;void WriteByCols(int rows, int cols) const;

private:enum {MAX = 50};

int matrix[MAX][MAX];};

Page 103: CSI 1340 Introduction to Computer Science II

C++ Implementation File - table.cpp

#include <iostream>#include “table.h”using namespace std; void Table::ReadByRows(int rows, int cols){

for (int r = 0; r < rows; r++)for (int c = 0; c < cols; c++)

cin >> matrix[r][c];} void Table::ReadByCols(int rows, int cols){ . . .

Page 104: CSI 1340 Introduction to Computer Science II

C++ Program - Main.cpp

#include <iostream>#include "table.h“using namespace std;int main( ) { Table t;

cout << “Enter a 3 X 8 matrix in column wise order: “<< endl;t.ReadByCols(3,8);cout << endl << “The matrix read was: “ << endl;t.WriteByRows(3,8);return 0;

}

Page 105: CSI 1340 Introduction to Computer Science II

C++ Program

Enter a 3 X 8 matrix in column wise order:1 6 2 5 3 4

The matrix read was:1 2 36 5 4

Page 106: CSI 1340 Introduction to Computer Science II

Public Section– Begins with the keyword, public, followed by a colon.– Includes the prototypes of public member functions.– Public members can be accessed by both member and

non-member functions.

C++ Class Terminology

Page 107: CSI 1340 Introduction to Computer Science II

Private Section– Begins with the keyword, private, followed by a colon.– Includes the private member variables (i.e., data) [may

also include private member functions].– Private members can only be accessed by member

functions [and friend functions].

C++ Class Terminology

Page 108: CSI 1340 Introduction to Computer Science II

class Time // class head{ // beginning of member listpublic: // public section

void setTime(int, int, int); // modification member functionsvoid printMilitary( ) const;void printStandard( ) const;

private: // private sectionint hour; // private member variablesint minute;int second;

}; // end of member list

Time Class - time.h

Page 109: CSI 1340 Introduction to Computer Science II

The class definition is placed with documentation in a header file that ends in .h

The member function implementations are often placed in a separate file that ends in .cpp

The implementation file must be added to a CodeWarrior project under Sources (along with Main.cp).

A program that wants to use a class must include the header file, e.g., #include “time.h”

Rules for C++ Class Files

Page 110: CSI 1340 Introduction to Computer Science II

The implementation file must also include the header file, e.g., #include “time.h”

Member functions differ from other functions in the following ways:– In the heading, the function’s name is preceded by the

class name and :: (the scope resolution operator)– Within the function, the private member variables are

accessed without passing them as parameters or declaring them as local variables.

Rules for C++ Class Implementations

Page 111: CSI 1340 Introduction to Computer Science II

class Time{public:

void setTime(int, int, int);void printMilitary( );void printStandard( );

private:int hour; // Note: the private member variablesint minute; // are not passed as parameters orint second; // declared as local variables

};

Time Class - time.h

Page 112: CSI 1340 Introduction to Computer Science II

C++ Implementation File - time.cpp

#include “time.h” void Time::setTime(int hr, int min, int sec){

hour = hr;minute = min;second = sec;

}

Page 113: CSI 1340 Introduction to Computer Science II

An object is declared using a class name followed by an instance name, e.g., Time t;

A member function is activated (called) by a non-member function (e.g.,in Main.cp) using the instance name, followed by a period, followed by the member function name, followed by its parameters, e.g.,

t.setTime(13,37,6);A member function is called by another member

function without the instance name, e.g., setTime(13,37,6);

Rules for C++ Object Creation & Use

Page 114: CSI 1340 Introduction to Computer Science II

A private member variable can only be accessed by a member function [or a friend function].

Non-member functions can access the private member variables only through the member functions.

Caution