CSC 101 Lecture Notes Week 7

CSC 101 Lecture Notes Week 7
Introduction to C++ Arrays
and Related C++ Programming Constructs


  1. Reading
    1. The rest of Chapter 8.
    2. Chapter 9 pp. 468-471, which covers for loops.
    3. Chapter 10 pp. 501-504 and pp. 534-544, which covers typedef and enum.
    4. All of Chapter 11.

  2. An initial array example.
    1. Suppose the specs for the grading program of assignment 4 were changed to allow up to 50 graded items, instead of just 5?
      1. This would have a major impact on the number of variables and parameters the program would need to declare.
      2. Specifically, the variables and parameters used for the percentage values, column sums, and sums of squares would all increase from 5 to 50.
    2. For example, here are before and after excerpts from the grading program main function:
      
      Before:
      
      
      int main() {
      
          int percent1, percent2, percent3, percent4, percent5;
                                      // Percentages for each graded item
      
          float sum1, sum2, sum3, sum4, sum5;
                                      // Column sums for each graded item
      
          float sum_sq1, sum_sq2, sum_sq3, sum_sq4, sum_sq5;
                                      // Sum of squares for each item plus TOTAL
      
      
          . . .
      
      }
      
      
      After:
      
      
      int main() {
      
          int percent1, percent2, percent3, percent4, percent5, ..., percent50;
                                      // Percentages for each graded item
      
          float sum1, sum2, sum3, sum4, sum5, ..., sum50;
                                      // Column sums for each graded item
      
          float sum_sq1, sum_sq2, sum_sq3, sum_sq4, sum_sq5, ..., sum_sq50;
                                      // Sum of squares for each graded item
      
      
          . . .
      
      }
      
    3. Clearly this is a mess.
      1. The solution is to use an array data structure to hold the percent, sum and sum of squares values.
      2. An array is a variable with a single name that can hold multiple values of the same type.
    4. Here is how the After version of the program above would look using arrays:
      int main() {
      
          int percent[50];            // Percentages for each graded item
          float sum[50];              // Column sums for each graded item
          float sum_sq[50];           // Sum of squares for each graded item
      
          . . .
      
      }
      

  3. Another example -- reading in a list of 1000 numbers and outputting them in reverse order.
    1. This is the example from pp. 594-595 of the book.
    2. Here's the program without using an array:
      
      
      
      ////
      //
      // This program reads a list of 1000 numbers from the terminal and prints them
      // back out to the terminal in reverse order.
      //
      ////
      
      #include <iostream.h>
      
      int main() {
      
          int value1;                 // Variable for 1st value read
          int value2;                 // Variable for 2nd value read
          // ...
          int value1000;              // Variable for 1000th value read
      
          //
          // Read each number into successive variables.
          //
          cin >> value1;
          cin >> value2;
          // ...
          cin >> value1000;
      
          //
          // Print out the values in reverse order by accessing from the last
          // variable to the first.
          //
          cout << value1000 << endl;
          // ...
          cout << value2 << endl;
          cout << value1 << endl;
      
          return 0;
      }
      
    3. Here's the equivalent program with an array:
      
      
      
      ////
      //
      // This program reads a list of 1000 numbers from the terminal and prints them
      // back out to the terminal in reverse order.
      //
      ////
      
      #include <iostream.h>
      
      int main() {
      
          int values[1000];           // Array of 1000 values to be read from file
          int i;                      // Counter used as index for each valueut
      
          //
          // Initialize the array index to 0.
          //
          i = 0;
      
          //
          // Read each number into successive positions in the array.
          //
          while (i < 1000) {
              cin >> values[i];
              i++;
          }
      
          //
          // Print out the values in reverse order by accessing from the end of the
          // array to the beginning.
          //
          i = 999;
          while (i >= 0) {
              cout << values[i] << endl;
              i--;
          }
      
          return 0;
      }
      

  4. Some basic array concepts.
    1. Bounds start at 0, not 1.
    2. Arrays are accessed using an index expression.
      1. E.g., if a is an array variable, a[10] accesses the 10th element (starting from 0) of the array.
      2. For an integer variable i, a[i] accesses the ith element.
      3. Any legal integer expression can be used as the index, as in a[i + j * k / 10], which will access the element at the position computed by the index expression.
    3. Out of bounds references are a common program bug.
      1. E.g., if a program declares an array with 100 elements, and tries to access the 200th element, bad things happen.
      2. Specifically, the program tries to access an element the is out of bounds.
      3. C++ does not check for this condition, and the behavior of a program with out of bounds array references is very unpredictable.

  5. A handy new control construct for processing arrays -- the for loop.
    1. So far, we have used while in C++ for looping.
    2. An alternative form of loop uses the keyword for.
      1. A for loop does not provide any fundamentally new power in a C++ program.
      2. It is simply a sometimes more convenient form of loop, especially when dealing with arrays.
    3. As an example of for loops, here is the reverse list program from above, with the while loops replaced with the equivalent for loops.
      
      
      
      ////
      //
      // This program reads a list of 1000 numbers from the terminal and prints them
      // back out to the terminal in reverse order.
      //
      ////
      
      #include <iostream.h>
      
      int main() {
      
          int values[1000];           // Array of 1000 values to be read from file
          int i;                      // Counter used as index for each valueut
      
          //
          // Read each number into successive positions in the array.
          //
          for (i = 0; i < 1000; i++) {
              cin >> values[i];
          }
      
          //
          // Print out the values in reverse order by accessing from the end of the
          // array to the beginning.
          //
          for (i = 999; i >= 0; i--) {
              cout << values[i] << endl;
          }
      
          return 0;
      }
      
    4. Figure 1 is a dissection of the for loop.
      
      

      Figure 1: Dissecting the for loop.


      
      
    5. Note that for loops are not for use only with arrays.
      1. They can be used anywhere that a while loop can be used.
      2. The for loop is particularly useful when the loop body involves incrementing a counter or index value, which makes it handy for array processing.

  6. Dealing with arrays as a whole.
    1. C++ does not provide operations that manipulate arrays as a whole.
    2. Such operations are called aggregate operations.
    3. For example, there is no aggregate array assignment operation of the following form:
      
      
      
      int x[50];
      int y[50];
      
      x = y;          // Does NOT copy 50 elements from y to x
      
    4. To accomplish an element-by-element copy of one array to another, a loop must be used, as in
      
      
      
      int x[50];
      int y[50];
      int i;
      
      for (i = 0; i < 50; i++) {
          x[i] = y[i];
      }
      
    5. Similarly, there are no aggregate array operations for comparison, input/output, arithmetic, or returning from a function, as in
      
      
      
      if (x == y) ... // No
      
      cout << x;      // No
      
      x = x + y;      // No
      
      return x;       // No
      
    6. The only thing you can do with an array as a whole is to pass it as a parameter to a function, as in
      
      
      
      DoSomethingWithAnArray(x);
      

  7. A new data structure for use with arrays -- the enum type.
    1. Chapter 10 of the book presents the enumeration type, that is a convenient way to define named integer constants.
    2. Here is an example:
      
      
      
      enum DaysOfWeek {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
      
      
    3. This enum declaration has the same effect as declaring seven integer constants, as follows:
      
      
      
      const int SUNDAY = 0;
      const int MONDAY = 1;
      const int TUESDAY = 2;
      const int WEDNESDAY = 3;
      const int THURSDAY = 4;
      const int FRIDAY = 5;
      const int SATURDAY = 6;
      
    4. There are two advantages to using an enum in place of separate constant declarations:
      1. The enum declaration is more compact.
      2. The enum declaration defines a separate named type, that can be used for declaring variables and parameters.
    5. Here is an example of using an enumeration with an array:
      
      
      
      ////
      //
      // This program reads in seven integers that define the number of tasks to be
      // done on each day of the week, from Sunday through Saturday.  The task
      // numbers are stored in a seven-element array, indexed by a days-of-the-week
      // enumeration.
      //
      ////
      
      #include <iostream.h>
      
      enum DaysOfWeek {
          SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
      };
      
      int main() {
      
          int days[sizeof(DaysOfWeek)];       // Array holding task numbers
      
          //
          // Prompt for and input the number of tasks for each day.
          //
          cout << "Input seven integers for the number of tasks to do on Sun - Sat: ";
          cin >> days[SUNDAY] >> days[MONDAY] >> days[TUESDAY]
              >> days[WEDNESDAY] >>  days[THURSDAY] >> days[FRIDAY]
              >> days[SATURDAY];
      }
      
    6. As with for loops, an enumeration is not just for use with arrays.
      1. An enum can be used anytime an ordered set of constant values is needed.
      2. Enumerations are particularly handy for defining mnemonically meaningful array indices, as the preceding example illustrates.

  8. Passing arrays as parameters.
    1. When an array is passed as a parameter to a function, it is always automatically passed by reference.
    2. In declaring a function with an array parameter, the ampersand should not be used in the parameter declaration, since the array is already being passed by reference.
    3. C++ arrays cannot be passed as value parameters.
      1. This means that any modifications that are done to an array in a function will always change the array parameter that the function was called with.
      2. You need to remember this to avoid unintended changes to array parameters.
      3. To avoid changing an array parameter, the array must be copied to a local function variable, and changes made to the copy.


index | lectures | labs | handouts | assignments | solutions | grades | help