1 / 114

CSI 1340 Introduction to Computer Science II

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

aleda
Télécharger la présentation

CSI 1340 Introduction to Computer Science II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Computers • Computers are dumb • All boils down to simple operations on 0s and 1s • Forest vs. Trees • Not suitable for human consumption

  3. 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

  4. 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

  5. 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;

  6. Struct Example typedef int IDType; struct StudentRec { IDType studentID; float gpa; } fred; // Declare variable like this StudentRec jane; // or this

  7. 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

  8. 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.

  9. Self-Test Answer typedef char StringType[21]; struct PartType { int number; StringType name; int quantity; float price; } ; PartType part;

  10. 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 };

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

  12. 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

  13. 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:

  14. 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

  15. 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

  16. 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.

  17. sends the location (memory address) of the actual parameter CALLING BLOCK FUNCTION CALLED Pass-by-reference can change value of actual parameter

  18. 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);

  19. 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 ;

  20. Aggregate Parameter Passing void myFunc (PartType part ) // Value parameter { . . . } void myFunc (PartType& part ) // Reference parameter { . . . }

  21. Aggregate Return PartType initializePart ( ) { PartType part = {145, “nail”, 4000, 2.98}; return part; // Aggregate return }

  22. 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.

  23. 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

  24. CSI 1340Introduction to Computer Science II One-Dimensional Arrays

  25. 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.

  26. 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

  27. 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)

  28. 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)

  29. 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];

  30. 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)

  31. Using Arrays • Assigning values • Reading values • Writing values • Copying arrays

  32. 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;

  33. 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]; }

  34. 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];

  35. Aggregate Operation • An operation on a data structure as a whole. • C++ does NOT allow aggregate copy, comparison, or return operations on arrays.

  36. 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]) . . .

  37. Aggregate Operations NOT Allowed • Aggregate return. int x[5]; … return x; // Not allowed // Must pass an array as a parameter

  38. 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.

  39. 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; }

  40. 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; }

  41. 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];

  42. 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’;

  43. 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.

  44. CSI 1340Introduction to Computer Science II Multidimensional Arrays

  45. Two-Dimensional Arrays • Table of columns and rows

  46. 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

  47. 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)

  48. Initializing a 2D Array • Example for (row = 0; row < 2; row++) for (col = 0; col < 4; col++) grades[row][col] = 0;

  49. 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. . .)

  50. 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. .)

More Related