|
|||
|
This module once again uses files and folders within the tar file module4.tar. Finding the Average with Arrays, Part II - File Access Notice that average1.c features 3 separate for loops;
Let's take a look at lines 35 and 38,
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;
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;
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 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:
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
If the conditional is true, the program closes the appropriate files and exits the program; otherwise, it iterates over 2 loops;
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 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:
It's the next nested for loop in lines 42 thru 57 that contain the actual sorting algorithm.
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);
Continue to the Apply Section -> |
||
Website by Joshua Bleier |