Presentation is loading. Please wait.

Presentation is loading. Please wait.

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.

Similar presentations


Presentation on theme: "91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes."— Presentation transcript:

1 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes (storage cells). double a /* scalar */, b [6] /* array */; int c[4] /* array */; bool f[3] /* array */, g /* scalar */; double bool int double bool a b c f g Arrays are declared in the same way as the “scalar” variables we’re used to, and array and scalar declarations may be intermingled as shown above. Arrays of length 1 and scalars are NOT equivalent, though they may look so in the diagram above.

2 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 2 Initializing Arrays Array variables may be given initial values, int z[4] = { 3, 2, 4, 6 }; 3246 z ‘a’‘b’‘c’ s char s[3] = { ‘a’, ‘b’, ‘c’ }; When an initial value is specified, the array size may be omitted (the compiler can count). Thus: int z[] = { 3, 2, 4, 6 }; // same as above Character arrays are not usually initialized as shown above. Instread “string” constants are usually used (more on this later).

3 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 3 Array No-no’s Assume int a[6], b[6]; Arrays cannot be read (except for char arrays): cin >> a; // Illegal!! Arrays cannot be written (except for char arrays): cout << a: // Illegal!! Arrays cannot be assigned: a = b; // Illegal!! a = { 1, 2, 6, 3, 6, 6 }; // Illegal (only OK in declarations)!! Arrays cannot be compared: if (a != b) { // Illegal!! Arrays cannot be added, etc.: a = a + b; // Illegal!!

4 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 4 Array Element Selection (1) The individual elements of an array are numbered, starting with element zero, and may be selected using the […] operator. int z[4] = { 3, 2, 4, 6 }; 3246 z z[0]z[1]z[2]z[3] The “…” represents an integer expression. If an array has “n” elements, the expression should evaluate to a value between 0 and “n-1” inclusive, but there is essentially no protection against the inadvertent use of invalid “index” values. int a = 3, b = 2; z[a] = z[b]; // OK - z[3] gets z[2] z[a + b] = 0; // oops! z[a - b] = 0; // OK - z[1] gets zero z[((b * 2) + a) - 5] = 1; // OK - the expression can be // complex as we want

5 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 5 Array Element Selection (2) Once an array element has been selected, it can be used in all the ways that a scalar variable of the same type can be. If we have an array of int’s, for example, selected elements may be used wherever an int variable if permissable. int a[6], b[6], c, d;... cin >> a[3]; if (a[2] != b[3]) { cout << a[c]; b[d + 2]++; } a[b[3]] = 6; In particular, array elements may be passed “by reference”. void func (int &x) { // assume defined somewhere…... } func (a[2]); // OK

6 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 6 First Array Example (1) Problem: Program is to read in up to 10 values (terminated with a -1, not to be included in the 10) and write them out in reverse order. #include … void main (void) { int array[10], // space for values read count, // number of values read i, value; // read values into array // write out values in reverse order } // end main

7 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 7 First Array Example (2) // read values into array count = 0; // nothing read so far cout << “Enter up to 10 values…\n”; cin >> value; // read in first value // loop while we haven’t seen the terminating // value (-1) and the array isn’t full while ((value != -1) && (count < 10)) { array[count++] = value; // store value cin >> value; // and read another one } // if things are going well, “value” should contain -1 at // this point. if it doesn’t, we must have stopped looping // because the array was full (too many values were entered) if (value != -1) { cout << “Too many values entered.\n”; return; } // “count” now contains the number of values read. // this value may be zero (-1 entered immediately)

8 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 8 First Array Example (3) // write out values in reverse order cout << “The values are:\n”; for (i = count - 1; i >= 0; i--) { cout << array[i] << endl; } This code will work correctly even if no values are entered. If you find the for loop confusing, replace it with the equivalent while loop. i = count - 1; while (i >= 0) { cout << array[i] << endl; i--; } To output the values in their original order: cout << “The values are:\n”; for (i = 0; i < count; i++) { cout << array[i] << endl; }

9 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 9 First Array Example (4) This example program is flawed in that it involves two “magic numbers” - 10 (the maximum number of values) and -1 (the special terminating value). It would be much better if it were modified as shown below: void main (void) { const int max_values = 10, terminator = -1; int array [max_values] …... cout << “Enter up to “ << max_values << “ values … while ((value != terminator) && (count != max_values)) { … if (count == max_values) { … Expressions may be used in defining arrays provided that they evaluate to a constant value.

10 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 10 Bubble Sort (1) A bubble sort involves making one or more “passes” over the data to be sorted. On each pass the first value is compared to the second, the second to the third, and so on. If the two values compared are out of order, they are swapped (interchanged). To sort: Continue making passes over the data until we have a pass on which no swaps occur. The data is now sorted. A refinement: Make each pass one comparison shorter (after the first pass the largest value will have “bubbled” to the last position, and we need only worry about the preceding values). = compare and swap if necessary 1 2 3 4 5 6 7

11 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 11 Bubble Sort (2) const int max_vals = 100; int array[max_vals], count, i, temp, stop; bool swap_occurred; // on the first pass, we must compare all pairs stop = count - 1; // count = number of values do { // we haven’t had any swaps so far on this pass swap_occurred = false; for (i = 0; i < stop; i++) { if (array[i] > array[i + 1]) { // values are out of order temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; swap_occurred = true; } // the next pass should do one less comparison stop--; } while (swap_occurred);

12 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 12 Selection Sort (1) In a selection sort, we begin by comparing the first array element with each of the following elements (with values getting interchanged when they are out of order). Then we compare the second array element with each of the following elements, and so on, until we have compared the second last element with each of the following elements (e.g with to the last element). first pass: compare the first element to all following elements second pass: compare the second element to all following elements last pass: compare the second last element to the last element

13 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 13 Selection Sort (2) const int max_vals = 100; int array[max_vals], count, i, j, temp; // assume that "count" contains the number // of values stored in the array (the number of // values to be sorted) // sort array for (i = 0; i < (count - 1); i++) { for (j = i + 1; j < count; j++) { if (array[i] > array[j]) { // values are out of order temp = array[i]; array[i] = array[j]; array[j] = temp; }

14 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 14 Arrays as Function Parameters (1) Arrays can be passed to functions (e.g. an array declared in one function can be made available to other functions). This is always done “by reference”, but there is no ‘&’ in the parameter declaration. Instead call by reference is implied by the fact that we’re dealing with an array. void func (int a, int &b, int c[]) {... } call by value call by reference call by reference (array case) “a” is an integer variable. the calling function must supply a value, and “a” is initialized with this value. “b” is a reference to an integer variable. the calling function must supply an integer variable, and “b” is initialized by being made to refer to this variable. “c” is a reference to an array of integers. the calling function must supply an integer array (of any length), and “c” is initialized by being made to refer to this array.

15 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 15 Arrays as Function Parameters (2) void func (int a, int &b, int c[]) {... } void main (void) { int x, y[6], z = 3;... func (z * 4, x, y); … } 3 12 a b c x y z Every operation upon “c” will apply to “y”. If the functions outputs c[0], the value in y[0] will get displayed, and so on.

16 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 16 Array Parameter Example (1) No length is normally specified in declaring an array parameter, and any length of array may be supplied by the calling function. This is very useful, but does require that we somehow let the called function know how many array elements are to be processed. This is normally done by passing the number of elements separately, as in the example below. void write_array (int n, int array[]) { int i; for (i = 0; i < n; i++) { cout << array[i] << endl; } This function prints out the first “n” elements of the array passed to it. This may or may not be the entire array (the function neither knows or cares).

17 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 17 Array Parameter Example (2) void main (void) { int m[50], s[12];... cout << “The elements of m are:\n”; write_array (50, m); // output all of array m cout << “The elements of a are:\n”; write_array (12, s); //output all of array s cout << “The first ten elements of m are:\n”; write_array (10, m); // OK... write_array (100, m); // Oops - an error!!... } While it is OK to have “write_array” output only the first part of an array, it is an error to try and output more elements than there actually are. Such errors will not be detected by the compiler and can be tricky to track down. Modifying “non-existant” array elements can, and normally will, result in very peculiar program behaviour.

18 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 18 Array Input Function // reads a list of of up to "max_values" values (terminated by // -1) into "array". sets "actual_values" to the number of // values actually read (possibly zero). returns true if the // complete list of values entered was sucessfully processed // and false otherwise (too many values entered). bool read_array (int max_values, int array [] int &actual_values) { int value; actual_values = 0; // nothing read in so far for (;;) { cin >> value; if (value == -1) { // input is complete return true; } if (actual_values == max_values) { // the user has entered too many values return false; } // store the value in the array and increment our counter array[actual_values++] = value; } // end for (;;) // no return required because we can't get here }

19 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 19 Bubble Sort Function // sorts array in ascending order void bubble_sort (int n /* array size */, int array[]) { int stop, temp, i; bool swap_occurred; stop = n - 1; // the first pass goes all the way do { swap_occurred = false; // no swaps so far this pass for (i = 0; i < stop; i++) { if (array[i] > array[i + 1]) { // values are out of order temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; swap_occurred = true; } stop--; // stop one place shorter next time around } while (swap_occurred); }

20 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 20 Sample Main Function void main (void) { const int max_vals = 100; int array[max_vals], count; // read in a list of values cout << "Enter a list of values (terminated by -1).\n: "; if (!read_array (max_vals, array, count)) { cout << "Array read failed (too many values).\n"; pause (); return; } // "count" now contains the number of values read // sort the array bubble_sort (count, array); // output the array cout << "The values in ascending order are\n"; write_array (count, array); pause (); }

21 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 21 Rainfall Example (1) Problem: We have a collection of of rainfall readings and want to output the number of days for which the rainfall is: from 0 to 4.9999 mm from 5 to 0.9999 mm... from 40 to 44.999 mm 45 and over mm 10 categories in total To solve this problem, we will make use of an array of ten counters (one for each category). The program will begin by setting all of these counters to zero. This is easier than specifying an initial value for the array, and more adaptable (what if we decide we want 100 categories?). int counters [10]; // one per category int i; double rainfall; for (i = 0; i < 10; i++) { counters[i] = 0; }

22 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 22 Rainfall Example (2) Next we loop, obtaining and processing readings. for (;;) { // obtain next reading and store in “rainfall”. // break out of loop if at the end of the data.... // compute counter array index and // increment the corresponding counter i = (int) (rainfall / 5); if (i > 9) { i = 9; } counters[i]++; // counters[i] = counters[i] + 1 } // end for (;;) // “counters” now contains the desired values See sample program rainfall.cpp.


Download ppt "91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes."

Similar presentations


Ads by Google