1.14k likes | 1.31k Views
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
E N D
CSI 1340Introduction 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 Composing primitives to view as a single object • Primitive data types Bit groupings and logical operations • Functions/Methods Logical units of operations
APPLICATION REPRESENTATION 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 int y; y = 25; Data Abstraction How do we provide abstraction for data? • Primitive data types (e.g., int, char, float, double) • Encapsulation: separation of physical representation from logical use
Record Next level of data abstraction • Composing groupings of primitive data types • Record: collection of related data items of different types struct TypeName { DataType MemberName; . . . } ; TypeName variablename;
Struct Example typedef int IDType; struct StudentRec { IDType studentID; float gpa; } fred; // Declare variable like this StudentRec jane; // or this
Struct Member Access • The member selection operator (period . ) is used between the variable name and the member identifier to access individual members of a record type variable. EXAMPLES fred.studentID fred.gpa
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.
Self-Test Answer typedef char StringType[21]; struct PartType { int number; StringType name; int quantity; float price; } ; PartType part;
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 };
Aggregate Struct Assignment PartType oldPart = { 145, “nail”, 4000, 2.98 } ; PartType newPart; newPart = oldPart; // Aggregate assignment
2 content slot # 522 523 524 525 Referencing Memory • Memory is like a shelf of slots • Each slot has a number and some content value
By value By reference “My shelf slot contains the number 2” “My shelf slot is number 523” Referencing Memory You can refer to a shelf slot in one of two ways:
By Reference “My shelf slot is number 523” • By reference tells you where the original content lives • You can directly access the shelf slot using the slot number to change the content
By Value “My shelf slot contains the number 2” • By value only gives you a copy of the value of the slot contents • You can change your copy of the slot contents • This does not change the actual slot contents
CALLING BLOCK FUNCTION CALLED Pass-by-value sends a copy of the contents of the actual parameter the actual parameter cannot be changed by the function.
sends the location (memory address) of the actual parameter CALLING BLOCK FUNCTION CALLED Pass-by-reference can change value of actual parameter
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);
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 ;
Aggregate Parameter Passing void myFunc (PartType part ) // Value parameter { . . . } void myFunc (PartType& part ) // Reference parameter { . . . }
Aggregate Return PartType initializePart ( ) { PartType part = {145, “nail”, 4000, 2.98}; return part; // Aggregate return }
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.
Struct Aggregate Operations Aggregate Operation I/O No Assignment Yes Arithmetic No Comparison No Parameter passage Ref. or Value Return as fcn’s return value Yes
CSI 1340Introduction to Computer Science II One-Dimensional Arrays
3 1 13 32 4 11 7 9 One-Dimensional Array • Collection of related items of the same type that are stored sequentially in memory and are accessed using the same name.
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
Accessing Array Components • Example num[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)
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)
Self-Test 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 float FArray[24]; char LastName[16]; // must reserve a space for ‘\0’ int IArray[500];
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)
Using Arrays • Assigning values • Reading values • Writing values • Copying arrays
Assigning Values to Arrays • Declaration int squares[3] = {0, 1, 4}; int cubes[ ] = {0, 1, 8, 27}; • Within a loop int squares[30]; for (i=0; i < 30; i++) squares[i] = i * i;
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]; }
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];
Aggregate Operation • An operation on a data structure as a whole. • C++ does NOT allow aggregate copy, comparison, or return operations on arrays.
Aggregate Operations NOT Allowed • Aggregate copy x = y; // Not allowed for (i = 0; i <= 9; i++) // Correct x[i] = y[i]; • Aggregate comparison of arrays if (x = = y) // Not allowed for (i = 0; i <= 9; i++) // Correct if (x[i] = = y[i]) . . .
Aggregate Operations NOT Allowed • Aggregate return. int x[5]; … return x; // Not allowed // Must pass an array as a parameter
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.
Array Example void ZeroOut (float[ ], int); // Prototype float num[10]; // Declaration ZeroOut (num, 10); // Call void ZeroOut (float arr[ ], int nElements) // Function { for (int i = 0; i < nElements; i++) arr[i] = 0.0; }
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; }
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];
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’;
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.
CSI 1340Introduction to Computer Science II Multidimensional Arrays
Two-Dimensional Arrays • Table of columns and rows
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]; // Error int matrix[y][y]; // Works
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)
Initializing a 2D Array • Example for (row = 0; row < 2; row++) for (col = 0; col < 4; col++) grades[row][col] = 0;
Reading a 2D Array by Row • Assume that the array is the following 8 3 4 5 9 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. . .)
Reading a 2D Array by Column • Example 8 3 4 5 9 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. .)