San Diego State University logo
ME 203

Module 4.2 - More Complex Arrays


This module once again uses files and folders within the tar file module4.tar.

Finding the Average with Arrays, Part II - File Access
Let's start this section with average1.c , which is like average0.c, but stores 10 numbers, and extracts these, from a file called average1.dat.

Notice that average1.c features 3 separate for loops;

  • the first one extracts the numbers from the file average1.dat (via the scanf function we first saw in Module 1.2),
  • the second prints out the values just inserted into the array, and
  • the third sums the values in the arrays for the calculation of the average.

Let's take a look at lines 35 and 38,

fscanf(fp, "%f", value);
box[i] = value;

Here, the initial loop reads in a value from the file average.dat (Pointed to by the file pointer fp), and puts it into the ith position of the array box.

The next loop displays the contents of box via the printf statement. The final loop sums all the values of the array box into ave, then divides by n, the total number of values stored in box. Here are lines 50 & 52;

ave = 0.0;
     ave += box[i];

In line 50, we initialize ave to 0 (and no, as a matter of fact, we won't stop beating to death the importance of this step), and in line 52, we're summing the values of box in ave, using the the C += operator, which adds the value of the right side to the value of the left side, and puts the result in the left side variable.

Look at line 56;

ave /= (float) n;

As you might guess, /= performs exactly like +=, except it divides the left side variable by the right side one, and places the result in the left side. In addition, the operator (float) typecasts the variable n so that it behaves as a float in the current operation; otherwise, the division of a float by an integer would yield an integer result and would round that result, making the result inaccurate. Line 57 prints the result.

Finding the Dot Product of 2 Vectors
Next, let's take a look at dot.c, which computes the dot product of two vectors (We'll use vector and array interchangeabley over this portion of the Module, as vectors are one-dimensional arrays).

The dot product of two vectors is the sum of the product of each position of the vectors; for vectors a & b, the calculation is:

(a[0] * b[0]) + (a[1] * b[1]) + ... + (a[n-1] * b[n-1])

It requires that the 2 vectors be of the same length. dot.c tests for this, in the if-then conditional at line 26, after it

  • performs the appropriate declarations and initialization of variables in lines 6 through 16 , and
  • tests to make sure that the appropriate files exist for opening and accessing in lines 18 through 21.

if(n1 != n2) {
  printf("you cannot do a dot product of v of diff sizes\n");

If the conditional is true, the program closes the appropriate files and exits the program; otherwise, it iterates over 2 loops;

  • The first loop in lines 36 through 39 extract the array values from the files dot1.dat and dot2.dat
  • The second loop (Lines 43 through 45) performs the actual dot product calculation:

    dotp += vector1[i] * vector2[i];

Finally, we print the dot product generated by this program into the file dotout.dat; fprintf, as you may have guessed, does what printf does, except it prints to a file instead of standard out. This print to file takes place in line 46, and in line 47 we close that file, and end the program.

Sorting the Values in an Array
In sort.c, we use a non-optimal method for sorting the elements in an n-element array.

Computer Science texts on Algorithms dedicate entire chapters to sorting algorithms and how to their complexity. Our algorithm is one of the slowest ever considered (it is an inefficient form of Selection Sort, covered by Wikipedia and summarized by a former student of Western Kentucky University), but it is relatively easy to grasp and therefore a useful learning tool.

We've seen the workings of the initial 40 lines of code before; to summarize:

  • Apropriate libraries are included and the program begun in Lines 1 thru 5.
  • We declare variables in lines 6 thru 9,
  • lines 11 thru 16 confirm that the data file exists,
  • line 19 scans in the first number in the file (the array size), and
    • lines 21 thru 31 make sure the size conforms to what the program can handle;
  • The printf statement and for loop in lines 33 thru 40 reads the data in from the file, prints it out in the current order, and stores it in our array.

It's the next nested for loop in lines 42 thru 57 that contain the actual sorting algorithm.

/* sort the data */
for(i = 0; i < n; i++) {
   for(j = i+1; j < n; j++) {
      /* take an element, hold in hand, and
         loop over all the NEXT ones */
      t1 = vector[i];

      /* grab the next element */
      t2 = vector[j];

      /* check to see if need to swap */
      if (t1 > t2) {
         vector[i] = t2;
         vector[j] = t1;
      }
   }
}

Briefly, the above code takes the first array value (line 46), and compares that value to all the ones after it (within the inner for loop in lines 48 thru 56);

  • if the algorithm finds a value smaller than the first one (line 52)
    • it swaps those values (lines 53 and 54).
  • When it finishes the inside for loop, we know that the smallest number is in the first array position
    • The outer for loop moves to the value in the next array position, and by comparing it to all the values after it, we make sure that position has the next smallest value.
  • when we've gone thru positions 0 thru n-1 of the array, we have a completely sorted array, from smallest to largest.

Continue to the Apply Section ->

Website by Joshua Bleier