1 / 34

Arrays: Input, Process, Overwrite

Learn how to quickly create and access 20 temperature variables in memory using arrays. Overwrite the last entered value and calculate the average.

wbasil
Download Presentation

Arrays: Input, Process, Overwrite

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

  2. Input, Process, Overwrite // input 20 temps and calculate an avg double sum = 0, temp, avg; for (inti=0; i<20; i++) { cout << "Enter a temp: "; cin >> temp; // overwrites the last sum += temp; // temp value entered } avg = sum / 20; There is only one temperature in memory at a time!

  3. Input, Process, Overwrite Question: How can we quickly create 20 temperature variables that are easy to access? (And so keep ALL temps in memory once they are entered)? Answer: Arrays

  4. Array Definition: A sequence of values in memory (called Elements) where: • each Element is the same Data Type - the number of Elements (size) is constant

  5. Array Declaration Syntax: type identifier [size] ; where size is a Literal or Constant Integer. Examples: int score[15]; constint NUM_TEMPS = 20; float temp[NUM_TEMPS];

  6. Array Declaration Syntax: type identifier [size] ; size can NOT be a variable! This is a Syntax Error intnumTemps = 20; float temp[numTemps];

  7. Array Declaration Semantics: type identifier [num] ; allocates a sequence of num locations of type type, indexed 0 to (num – 1)

  8. Array Declaration Semantics: Example int a[5];

  9. Array Accessing an element: identifier [index] where index is an integer between 0 and (numOfEle – 1) This can be used the same as a Variable of the declared Type.

  10. Array Accessing an element: identifier [index] The index is thought of as a subscript, so: list[3] is often translated into English as: "list sub 3"

  11. Array Example 1: int a[5]; a[1] = 12; a[4] = -3; // array index out of // bounds error! a[5] = 0;

  12. Array Example 2: double sum = 0, temp[20], avg; for (inti=0; i<20; i++) { cout << "Enter a temp: "; cin >> temp[i]; sum += temp[i]; } avg = sum / 20; And: all 20 temps entered are still in memory!

  13. Array Style (Best Practice): Use a constant for num. of elements constint NUM_TEMPS = 20; double sum=0, temp[NUM_TEMPS], avg; for (inti=0; i<NUM_TEMPS; i++) { cout << "Enter a temp: "; cin >> temp[i]; sum += temp[i]; } avg = sum / NUM_TEMPS;

  14. Array Issue: At the time a program is written, the number of elements: - may not be known, or - may need to vary (a different number each time the program is used)

  15. Partial Array Solution: a Partial Array consists of • an array where only the first n elements is in use, where n is 0 to (NumElements – 1) • an integer variable that is the number of elements in use (n). • [usually] an integer constant that is the MAX number of elements.

  16. Partial Array Example: // partial array of temperatures, max 20 constintMAX_TEMPS = 20; intnumTemps = 0;// start ”empty” double temp[MAX_TEMPS]; The program must ensure 0 <= numTemps < MAX_TEMPS

  17. Partial Array Maximum Number of Elements: When the Maximum Number of Elements is not given in the problem, the programmer must make an ”intelligent guess”. Example: a list of test scores. What is the maximum number of tests any user would need for this program? Guess too small: your program is unusable. Guess too large: your program wastes memory.

  18. Partial Array Example: constintMAX_TEMPS = 20; intnumTemps = 0; // start ”empty” double temp[MAX_TEMPS]; cout << ”How many temps? (0-20)”; cin >> numTemps; //should validate 0-20 for (inti = 0; i < numTemps; i++) { ...temp[i]...// process the temps }

  19. General Algorithm for Arrays For most problems involving an array, use a for loop constintMAX_ELE = whatever; intnumEle; type a[MAX_ELE]; for (inti = 0; i < numEle; i++) { ... // do something with a[i] }

  20. Common Algorithms Initialize constint MAX = 100; double a[MAX]; intnum = 0; // for Partial Array // set ALL elements to "unused"/"empty" for (inti=0; i < MAX; i++) { a[i] = 0.0; }

  21. Common Algorithms Populate (User Input) do { // validate number of values used cout << "How many values? "; cin >> num; } while (num < 0 || num > MAX); for (inti=0; i < num; i++) { cout << "Enter a value: "; cin >> a[i]; }

  22. Common Algorithms Sum // sum of all values in the array double sum = 0.0; for (inti=0; i < num; i++) { sum += a[i]; }

  23. Common Algorithms Max // find the highest value double m = a[0]; // start with first ele for (inti=1; i < num; i++) { if (a[i] > m) m = a[i]; }

  24. Common Algorithms Min // find the lowest value double m = a[0]; // start with first ele for (inti=1; i < num; i++) { if (a[i] < m) m = a[i]; }

  25. Common Algorithms Min // find the lowest value double m = a[0]; // start with first ele for (inti=1; i < num; i++) { if (a[i] < m) m = a[i]; else // common mistake! m = something else; }

  26. Common Algorithms Print // print all values in an array for (inti=0; i < num; i++) { cout << a[i] << ” ”; }

  27. Common Algorithms Append to a Partial Array // add a new value to the end of the list double newValue; ... if (num < MAX) {// check if room available a[num] = newValue; num ++; } // else array is full, can not append

  28. Common Algorithms Remove from Partial Array

  29. Common Algorithms Remove from a Partial Array // remove r’thele from the list & "save" it int r; // index of the element to remove double rem; // copy of removed value ... if (r>=0 && r<num) { // ensure r is "in range" rem = a[r]; // save a copy (optional) num--; // one less item in list for (inti = r; i < num; i++) a[i] = a[i+1]; a[num] = EMPTY_VALUE; // optional } // else r is out of range, can't remove

  30. Common Algorithms Linear Search // find INDEX where value found; -1=not found double searchValue; ... int found = -1; // assume not found for (inti=0; i<num; i++) { if (a[i] == searchValue) found = i; // found in a[i] } // after loop: found = -1 means "not found" // found != -1 means "found in this element"

  31. Common Algorithms Linear Search // find INDEX where value found; -1=not found double searchValue; ... int found = -1; // assume not found for (inti=0; i<num; i++) { if (a[i] == searchValue) found = i; else // common mistake! found = -1; }

  32. Common Algorithms (Easy to Memorize) Bubble Sort for (inti=0; i<num-1; i++) { for (int j=i+1; j<num; j++) if (a[i] > a[j]) { // swap a[i] with a[j] double t = a[i]; a[i] = a[j]; a[j] = t; } }

  33. Common Algorithms Bubble Sort: Decreasing Order (Hi to Low) for (inti=0; i<num-1; i++) { for (int j=i+1; j<num; j++) if (a[i] <a[j]) { // change > to < // swap a[i] with a[j] double t = a[i]; a[i] = a[j]; a[j] = t; } }

  34. Vocabulary

More Related