DOC PREVIEW
UW CSE 142 - Study Notes

This preview shows page 1-2 out of 6 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 6 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 6 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 6 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

O-1O-1CSE 142Computer Programming IArrays© 2000 UW CSEO-2OverviewConcepts this lectureData structuresArraysSubscripts (indices)O-3Chapter 88.1 Declaration and Referencing8.2 Subscripts8.3 Loop through arrays8.4 & 8.5 Arrays arguments and parameters8.6 ExampleO-4Rainfall Data RevisitedGeneral task: Read daily rainfall amounts and print some interesting information about them.Input data: Zero or more numbers giving daily rainfall followed by a negative number (sentinel).Example input data: 0.2 0.0 0.0 1.5 0.3 0.0 0.1 -1.0Empty input sequence: -1.0O-5Rainfall AnalysisPossible things to report:How many days worth of data are there?How much rain fell on the day with the most rain?On how many days was there no rainfall?What was the average rainfall over the period?On how many days was the rainfall above average?What was the median rainfall?Question of the day: Can we do all of these while we read the data?O-6Rainfall Analysis (cont)For some tasks (median, number of days above average), we need to have all the data before we can do the analysis.Where do we store the data?Lots of variables (rain1, rain2, rain3, rain4, …)?AwkwardDoesn’t scaleNeed something betterO-2O-7Data StructuresFunctions give us a way to organize programs.Data structures are needed to organize data, especially:large amounts of datavariable amounts of datasets of data where the individual pieces are related to one anotherIn this course, we will structure data usingarraysstructscombinations of arrays and structsO-8ArraysDefinition: A named, ordered collection of variables of identical typeName the collection (rain); number the elements(0 to 6)06...1.00.20.00.01.40.10.0double rain[7];1Example: rainfall for one weekO-9Accessing VariablesVariable access:rain[0] is 1.0rain[6] is 0.02.0∗rain[4]is 2.8.06...1.00.20.00.01.40.10.0double rain[7];1Rainfall for one weekO-10Array Declaration Syntaxtype name[size]; double rain[7];array declarationsize must be an int constantO-11Array Terminologydouble rain[7];rain is of type array of double with size 7.rain[0], rain[1], ... , rain[6] are the elements of the array rain. Each is a variable of type double.0,1, ... , 6 are the indices of the array. Also called subscripts.The bounds are the lowest and highest values of the subscripts (here: 0 and 6).O-12Rainfall Analysis (cont.)Strategy for processing data if we need all of it before we can process it:Read data and store it in an arrayAnalyze data stored in the arrayKey detail: In addition to the array, we need to keep track of how much of the array currently contains valid data.O-3O-13Keeping Track of Elements In-UseSince an array has to be declared a fixed size, you often declare it bigger than you think you’ll really need#define MAXRAINDAYS 400 int rain[MAXRAINDAYS];How do you know which elements in the array actually hold data, and which are unused extras?1. Keep the valid entries together at the front2. Record number of valid entries in a separate variableO-14Keep the valid entries togetherrain0MAX RAIN DAYS - 167numRainDays7for (k=0; k < numRainDays; k++) {/* process rain[k] */}! ! ! !O-15Print # Days Above AverageAlgorithm:Read data into an arrayCompute average rainfall (from array)Keeping track of total # of daysCount # days above average (from array)Print resultO-16Declarations/* Maximum # of days of input data */#define MAXRAINDAYS 400 int main(void) { /* rainfall data is stored in *//* rain[0..numRainDays-1] */double rain[MAXRAINDAYS];int numRainDays ;double rainfall; /* current input value */double rainTotal; /* sum of input rainfall values */double rainAverage; /* average rainfall *//* # days with above average rainfall */int numAbove;int k;O-17Read Data Into Array/* read and store rainfall data */printf("Please enter rainfall data.\n");numRainDays = 0;scanf("%lf", &rainfall);while (rainfall >= 0.0) {rain[numRainDays] = rainfall;numRainDays++;scanf("%lf", &rainfall);}O-18Calculate Average/* calculate average rainfall */rainTotal = 0;for (k = 0; k < numRainDays; k++) {rainTotal = rainTotal + rain[k];}rainAverage = rainTotal / numRainDays;double rain[MAXRAINDAYS]; /* rainfall data*/int numRainDays; /* # of data values */double rainTotal; /* sum of input values*/double rainAverage; /* average rainfall*/int k;We should make a test to avoid a divide by zeroO-4O-19Calculate and Print Answer/* count # of days with rainfall above average */numAbove = 0;for (k = 0; k < numRainDays; k++) {if (rain[k] > rainAverage)numAbove++;} /* Print the result */printf("%d days above the average of %.3f.\n", numAbove, rainAverage);double rain[MAXRAINDAYS]; /* rainfall data*/int numRainDays; /* # of data values */double rainAverage; /* average rainfall */int numAbove; /* # of days above average */int k;O-20Index RuleRule: An array index must evaluate to an int between 0 and n-1, where n is the number of elements in the array. No exceptions!Example:rain[i+3+k] /* OK as long as 0 ≤ i+3+k ≤ 6 */The index may be very simplerain[0]or incredibly complexrain[(int) (3.1 * fabs(sin (2.0*PI*sqrt(29.067))))]O-21C Array Bounds are Not Checked#define DAYS_IN_WEEK 7double rain[DAYS_IN_WEEK] ;int index ;index = 900 ;...rain[index ] = 3.5 ; /* Is index out of range?? */You need to be sure that the subscript value is in range. Peculiar and unpleasant things can (and probably will) happen if it isn’t.O-22TechnicalitiesAn array is a collection of variablesEach element can be used wherever a simple variable of that type is allowed.Assignment, expressions, input/outputAn entire array can’t be treated as a single variable in CCan’t assign or compare arrays using =, ==, <, …Can’t use scanf or printf to read or write an entire arrayBut, you can do these things one element at a time.O-23“Parallel” ArraysA set of arrays may be used in parallel when more than one piece of information must be stored for each item.Example: we are keeping track of a group of students. For each item (student), we might have several pieces of information such as scoresO-24Parallel Arrays ExampleSuppose we have a midterm grade, final exam grade, and average score for each student.#define MT_WEIGHT 0.30#define FINAL_WEIGHT 0.70#define MAX_STUDENTS 200int num_student, midterm[MAX_STUDENTS],final[MAX_STUDENTS] ;double score[MAX_STUDENTS] ;O-5O-25Parallel Arrays Example/* Suppose we know the value of num_students, have read student i’s grades for midterm and final, and stored them in midterm[i] and final[i]. Now:Store a


View Full Document

UW CSE 142 - Study Notes

Download Study Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Study Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Study Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?