340 likes | 347 Views
Learn how to quickly create and access 20 temperature variables in memory using arrays. Overwrite the last entered value and calculate the average.
E N D
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!
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
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
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];
Array Declaration Syntax: type identifier [size] ; size can NOT be a variable! This is a Syntax Error intnumTemps = 20; float temp[numTemps];
Array Declaration Semantics: type identifier [num] ; allocates a sequence of num locations of type type, indexed 0 to (num – 1)
Array Declaration Semantics: Example int a[5];
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.
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"
Array Example 1: int a[5]; a[1] = 12; a[4] = -3; // array index out of // bounds error! a[5] = 0;
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!
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;
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)
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.
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
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.
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 }
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] }
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; }
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]; }
Common Algorithms Sum // sum of all values in the array double sum = 0.0; for (inti=0; i < num; i++) { sum += a[i]; }
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]; }
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]; }
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; }
Common Algorithms Print // print all values in an array for (inti=0; i < num; i++) { cout << a[i] << ” ”; }
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
Common Algorithms Remove from Partial Array
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
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"
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; }
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; } }
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; } }