1 / 43

Data Structures (Terminology)

Data Structures (Terminology). Static Set at compile time Dynamic Set at run time. Data Types. Simple or atomic data types char, int, float, double Structured data types struct, class. Aggregates/Collections/Containers of data types.

lcallahan
Download Presentation

Data Structures (Terminology)

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. Data Structures (Terminology) • Static • Set at compile time • Dynamic • Set at run time

  2. Data Types • Simple or atomic data types • char, int, float, double • Structured data types • struct, class

  3. Aggregates/Collections/Containers of data types • Stores collections of Atomic or Structured data types • Array, linked list • lists, stacks, queues, trees, graphs

  4. Arrays Collections of same data types • One-Dimensional 1D • We have seen already special case of Cstrings. • Two-dimensional 2D and more • Need to know how to declare,initialise access of elements, and pass arrays as function arguments.

  5. Recall that an Array is • A collection of adjacent data storage locations, each of which holds the same type of data. Each storage location is called an element of the array. • Each element is referred to via an index variable.

  6. Uses • Statistics • Averages, Standard deviations. • Lookup tables • For speed efficiency • games • Scores, locations of elements, etc • Information systems • List maintenance. • Once initialised can be manipulated: searched and sorted.

  7. Array Declaration • Syntax dataType arrayName [ ConstIntExpression ] The number of elements in an array is stated within square brackets, [ ]. • Examples const int POLY = 8; double angle [4]; int testScore [12]; double angle [POLY]; char password [8];

  8. Array Storage • Each array has sufficient memory reserved to hold the number of data items of the given type. • Declaring an array sets up the address of the first element. Addresses of all other elements are offsets from the starting address.

  9. Array Element Access • Syntax x = arrayName [ indexExpression ] arrayName [ indexExpression ] = x • Program access to each of the array elements is by referring to an offset from the array name. Array elements are counted beginning with zero.

  10. Array Element Access • double angle[4]; // declaration • Initialisation exampleangle [0] = 6.21; angle [1] = 15.89; angle [2] = 7.5; angle [3] = -45.7; Make sure all elements are initialised before use!

  11. Using Array Elements • Write the contents of an array element: cout << angle[2]; • Assign values to an array element: cin >> angle[3]; angle[6] = pow(axis,4); • Use it as an argument: y = sqrt(angle[0]); • Use it in an expression: x = 2.5 * angle[1] + 64;

  12. Array Component Access • for(index=0; index < arraySize; index++) myArray[index] = 0.0; • Clever trick to compute arraySize • arraySize = sizeof(myArray)/sizeof(myArray[0]) • sizeof( ) returns the total number of bytes reserved, we want the total number of elements, so we divide the total number of bytes by the size of one element. Zeros out an entire array. (Initialize every element to 0.0.)

  13. [ 0 ] [ 1 ] [ 2 ] [ 3] @#$ @#$ Offsets for int myarray[4]; Assume 4 bytes for an int starting address off set by one elem off set by two elem off set by three elem memory address myarray + 0 00023 myarray +1 00027 myarray + 2 00031 00035 myarray + 3 00039 myarray + 4 OUT OF BOUNDS myarray + 5 00043

  14. Initialise an array when you declare it double angle[4] = {16.21, 15.89, 7.5, -45.7}; double ATtoCG[5] = {.64, .89, .76, .83, .65}; int scores[12] = {210, 198, 203, 188, 200, 224, 220, 217, 211, 194, 197, 189}; double iota[8] = {0.0}; // sets all elements to zero

  15. Initialize an Array int scores[ ] = {210, 198, 203, 188, 200, 224, 220, 217, 211, 194, 197, 189}; char name[4] = {‘Z’, ‘o’, ‘l’, ‘a’}; char name[4] = “Zola”; // no braces or , char phrase [ ] = “Hello World”; Note

  16. Initialising an Array via the keyboardnItems computed by earlier trick double grade[10]; int index; nItems = sizeof(grade)/sizeof(grade[0]); for(index=0; index < nItems; index++){ cout<<“Enter a grade “; cin >> grade[index]; }

  17. Initialising an array from a data file // make sure that you specify enough space double grade[10]; int index; ifstream mydata; mydata.open(“mydata.dat”,ios::nocreate); index = 0; while(mydata >> grade[index]){ index++; } mydata.close();

  18. Fundamental algorithm for arrays: Traversing through an array • Use the for statement to sequence through an array. • Example: To total the contents of an array: nItems computed by earlier trick sum = 0; // initialise an accumulator for(index=0; index < nItems; index++) sum = sum + grades[index];

  19. Fundamental algorithm for arrays: Searching and arrayto obtain index of a element matching a specified key • Algorithm • needs following variables • int currIndex, targetIndex • Get key value from user or from a file • Set the currIndex to zero • Use a loop (probably a for loop) to cycle through the array. • Compare each element to the key. • If match is found • set target index to current index • If no match is found • set target index to –1 • return target index

  20. Example: Searching an integer array for a key value double find_Key(int data[], int key,int nItems) { int index; //current index int target; //target index for(index=0; index < nItems; index++){ if (data[index] == key){//compare elements to key target = index; return target; //if found bail out now! } } // if you get to here you haven't found key! return -1; //used by caller, indexes cannot be //negative. }

  21. Aggregate Assignment - NOT! • There are no aggregate assignments with arrays. That is, you may not assign one array to another. • int x[5] = {11, 22, 33, 44, 55}; //declaration only • int y[5]; • y = x; y[ ] = x[ ]; • if elements are atomic data then y[0] = x[2] is legal

  22. Arrays as Arguments Note! double find_max(int data[ ],int nItems){ double max = data[0]; for(index = 1; index < nItems; index++){ if (data[index] > max){ max = data[index]; } } return max; } note I start form 1 because we have used data[0] already

  23. Passing an Array/Element int temps[30]; find_max(temps,30); // correct no [ ] find_max(temps[3]);//Wrong! only refers toelement 4

  24. 1-D Array Review • Array Declaration int myArray [9]; • Array Initializationat time of declaration int myArray [9 ] = { 9, 9, 9, 8, 7, 6, 5, 4, 3}; • Array Initialsation after declaration int myArray[9]; myArray[0] = 9; myArray[1] = 9; myArray[2] = 9; myArray[3] = 8; myArray[4] = 7; myArray[5] = 6; myArray[6] = 5; myArray[7] = 4; myArray[8] = 3; use a loop to make more efficient!

  25. 1-D Array Review (cont) • Array Element Reference myArray [7] = 4; // value = 4 • Arrays are always passed by reference • All functions can affect arguments from caller • A const added to the formal parameter prevents changes to argument passed. • void myFunction(constint data[]); • Array in a Function Prototype void myFunction(int data[]); Explicitly specifying size is optional, it is usual to add an extra parameter that specifies number of elements in array being passed. void myFunction(int data[], int nItems);

  26. Two Dimensional Arrays: Tables first concepts • Everything about one dimensional arrays applies • Sometimes referred to as a table • Has rows and columns ex. multiplication table

  27. 2-D Array Declaration Number of rows Number of cols Syntax dataType arrayName [ Integer ] [Integer ] ; Example int highTemp [52] [7]; //52 rows of 7 ints double matrix [8] [8]; // checker board int roomSchedule [237] [13];

  28. 2-D Array Initialization int nums [3] [2] = {7, 4, 1, 8, 5, 2} OR int nums [3][2] = {{7,4},{1,8},{5,2}}; int rooms[3] [7] = { {17, 18,19, 110, 111, 112, 113}, {27, 28, 29, 210, 211,212, 213}, {37, 38, 39, 310, 311, 312, 313} };

  29. 2-D Array Initialization double ATtoCG[2] [3] = {.74, .79, .76, .83, .65, .89}; double ATtoCG[2] [3] = { {.74, .79, .76}, {.83, .65, .89} }; int scores[4] [3] = {210, 198, 203, 188, 200, 224, 220, 217, 211, 194, 197, 189};

  30. 2-D Array Initialization You can assign values to individual elements: ATtoGC [0] [0] = 0.74; ATtoGC [0] [1] = 0.79; ATtoGC [0] [2] = 0.76; ATtoGC [1] [0] = 0.83; ATtoGC [1] [1] = 0.65; ATtoCG [1] [2] = 0.89; Note order rows then columns

  31. A[0][0] A[1][0] A[0][1] A[1][1] A[0][2] A[1][2] A[0][3] A[1][3] Memory Diagram int A[2][4];

  32. Accessing a 2-D Array elements • Use nested loops. • outer for loop was for the rows • inner for loop was for the columns

  33. Example:- Creating a 2-D Array Multiplication table int timesTable[12][12]; for (row =0; row < 12; row++){ for (col=0; col < 12; col++){ timesTable[row][col]=(col+1)*(row+1); } } correction for 1 off problem, caused by array indexes starting from 0

  34. Loading a 2-D Array via keyboard int scores [4][3]; for(row=0; row<4; row++){ for(col=0; col<3; col++){ cout<<"Enter the value :"; cin>>scores[row][col]; } }

  35. Displaying a 2-D Array int scores[4][3]; for(row=0; row<4; row++) { for(col=0; col<3; col++) { cout << setw(6) << scores[row][col]; } cout << endl; // new line for each row }

  36. Using a 2D Array.LOOKUP TABLE • Typical use where you have N rows of 2 columns. • First Column represents a key, the second a value. • Problem given a key what is the associated value. • Example a lookup table for sin(x); • Why? speed efficiency

  37. Algorithm Needs variables double key; double SinTheta[360][2]; • Create lookup table. Either load from file or one off calculation at start. • Repeat as long as you want • ask for key (angle in degrees not radians) • search lookup table for associated value • for each row • if first element matches key • return associated value • if no match found return error value or default • display associated value

  38. Code (SEE DEMO) #include <iostream.h> #include <math.h> const double PI = 3.14159; double Lookup(double table[][2], double key); int main(void) { double angleKey; double SinOfAngle; double LookupTable[360][2]; int row; //Init lookup table for (row = 0; row<360; row++) { LookupTable[row][0] = row; LookupTable[row][1] = sin(PI*row/180.0); } //Init lookup table for (row = 0; row<360; row++) { cout << LookupTable[row][0] << "\t"<< LookupTable[row][1] << endl; } //Repeat as long as necessary do { cout << "Please enter an angle in degrees : "; cin >> angleKey; SinOfAngle = Lookup(LookupTable, angleKey); //Display associated value if (SinOfAngle > 1.0) cout << "Error unable to find angle in table" << endl; else cout << "The sin of " << angleKey << " is " << SinOfAngle << endl; } while (angleKey > 0); //use angleKey as sentinel return 0; } // end of program double Lookup(double Table[360][2], double key) { int row; const double epsilon = 0.002; for (row = 0; row < 360; row++) if (fabs(Table[row][0] - key) < epsilon) // remember problem with comparison of floats { cout << "Found key " << endl; return Table[row][1]; } //if you get to here you haven't found key //so return default or error code return 2.0; }

  39. Functions and 2-D Arrays • When calling functions that use 2D Arrays. The arrays are passed in a similar manner to 1D arrays. • In the prototypes and definition headers you must specify the second dimension. You can omit the first dimension. • int data[8][12]; • processArray(int vals[][12]);

  40. Passing subsets of 2D arraysThis is complicated – take your time! • A single row of a 2D array is a 1D array. • We can refer to a complete row by its subscript. • e.g. int Data[10][7]; //10 rows of 7 int’s • Is essentially a series of 10 1D arrays of 7 elements. • SO FOR THIS 2D array Data[0] refers to the first complete row, Data[1] the second and so on. • We can pass these subsets as function arguments to functions that accept 1D arrays. • E.g. double SumRow(int vals[],int nvals); • sum = SumRow(Data[0],7); //call to sum elements in 1st row • sum = SumRow(Data[1],7); //call to sum elements in 2nd row • This is confusing I know. You must be alert to the fact that sometimes Data[i] may refers to a complete row when Data is 2D or Data[i] refers to a single element when Data is 1D

  41. Arrays of strings • To store a list of strings • A string is a list of chars Example //un-initialised space for 10 lots of up to 30 chars char LastNames[10][30]; //declaration and initialisation of three strings char FirstNames[3][30] = {“Tom”, “Dick”, “Harry”};

  42. Interpretation FirstName[0] is “Tom” FirstName[1] is “Dick” FirstName[2] is “Harry”

  43. Using strcpy() recall strcpy(destination, source); To set LastName[0] to “Thorpe” strcpy(LastName[0],”Thorpe”); Recall that, LastName[0] = “Thorpe”; // is wrong

More Related