O-1 University of Washington Computer Programming I Lecture 14: Arrays © 2000 UW CSE.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Programming and Data Structure
An Array A sequence of elements of a particular type Each element in the array has an index which gives its position in the sequence An array is declared.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Kernighan/Ritchie: Kelley/Pohl:
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Introduction to Arrays.
Arrays H&K Chapter 8 Instructor – Gokcen Cilingir Cpt S 121 (July 13, 2011) Washington State University.
Enumerated Types 4 Besides the built-in types, ANSI C allows the definition of user-defined enumerated types –To define a user-define type, you must give.
O-1 University of Washington Computer Programming I Lecture 14: Arrays © 2000 UW CSE.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays 6.3Declaring Arrays 6.4Examples Using Arrays 6.5Passing.
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
R-1 University of Washington Computer Programming I Lecture 17: Multidimensional Arrays © 2000 UW CSE.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
1 ICS103 Programming in C Lecture 12: Arrays I. 2 Outline Motivation for One-dimensional Arrays What is a One-dimensional Array? Declaring One-dimensional.
Chapter 8 Arrays and Strings
Wednesday, 11/6/02, Slide #1 CS 106 Intro to CS 1 Wednesday, 11/6/02  QUESTIONS?? – HW # 4 due Monday  Today:  Return HW #3  Arrays (Chap. 10)  Reading:
H2-1 University of Washington Computer Programming I Lecture 10: Loop Development and Program Schemas © 2000 UW CSE.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic concepts and uses of arrays ❏ To be able to define C.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 8 Arrays and Strings
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
C Lecture Notes 1 Arrays Lecture 6. C Lecture Notes 2 6.1Introduction Arrays –Structures of related data items –Static entity – same size throughout program.
CS 161 Introduction to Programming and Problem Solving Chapter 19 Single-Dimensional Arrays Herbert G. Mayer, PSU Status 10/8/2014 Initial content copied.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
1 Chapter 7 Arrays. 2 Topics 7.1 Arrays Hold Multiple Values 7.2 Accessing Array Elements 7.3 No Bounds Checking in C Array Initialization 7.5 Processing.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
ICS103 Programming in C Lecture 11: Arrays I
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
ICS103: Programming in C 7: Arrays Muhamed F. Mudawar.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
CSE 251 Dr. Charles B. Owen Programming in C1 Intro to Arrays Storing List of Data.
© Janice Regan, CMPT 128, January CMPT 128: Introduction to Computing Science for Engineering Students Introduction to Arrays.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Introduction to programming in java Lecture 21 Arrays – Part 1.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Data Storage So far variables have been able to store only one value at a time. What do you do if you have many similar values that all need to be stored?
142 M -1 Arrays Chapter 8 Motivation: to deal with large amounts of data e.g sorting values: Input: 10, 15, 4, 15, 17, 3, 12, 36, 48, 32, 9, 21 Want the.
Chapter VII: Arrays.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Computer Programming BCT 1113
New Structure Recall “average.cpp” program
Arrays, Part 1 of 2 Topics Definition of a Data Structure
ARRAYS Lecture
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
EKT150 : Computer Programming
Lecture 18 Arrays and Pointer Arithmetic
Arrays Outline Introduction Arrays Declaring Arrays
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Initializing variables
Arrays, Part 1 of 2 Topics Definition of a Data Structure
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
ICS103 Programming in C Lecture 12: Arrays I
ARRAYS ..
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Presentation transcript:

O-1 University of Washington Computer Programming I Lecture 14: Arrays © 2000 UW CSE

O-2 Overview Concepts this lecture Data structures Arrays Subscripts (indices)

O-3 Chapter Declaration and Referencing 8.2 Subscripts 8.3 Loop through arrays 8.4 & 8.5 Arrays arguments and parameters 8.6 Example

O-4 Rainfall Data Revisited General 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: Empty input sequence:

O-5 Rainfall Analysis Possible 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? Can we do all of these while we read the data?

O-6 Rainfall 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, …)? Awkward Doesn’t scale Need something better

O-7 Data Structures Functions give us a way to organize programs. Data structures are needed to organize data, especially: large amounts of data variable amounts of data sets of data where the individual pieces are related to one another In this course, we will structure data using arrays structs combinations of arrays and structs

O-8 Arrays Definition: A named, ordered collection of variables of identical type Name the collection (rain); number the elements (0 to 6) Example: rainfall for one week Variable access: rain[0] is 1.0 rain[6] is  rain[4] is double rain[7]; 1

O-9 Array Terminology type name[size]; double 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). array declaration size must be an int constant

O-10 Rainfall Analysis (cont.) Strategy for processing data if we need all of it before we can process it: Read data and store it in an array Analyze data stored in the array Key idea: In addition to the array, we need to keep track of how much of the array currently contains valid data.

O-11 Keeping Track of Elements In-Use Since an array has to be declared a fixed size, you often declare it bigger than you think you’ll really need #define MAXRAINDAYS 400 intrain[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 front 2.Record number of valid entries in a separate variable

O-12 Keep the valid entries together rain 0 MAX RAIN DAYS numRainDays 7 for (k=0; k < numRainDays; k++) { /* process rain[k] */ } ! !

O-13 Print # Days Above Average Algorithm: Read data into an array Compute average rainfall (from array) Count # days above average (from array) Print result

O-14 Declarations /* 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-15 Read 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-16 Calculate 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 zero

O-17 Calculate 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-18 Index Rule Rule: 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 simple rain[0] or incredibly complex rain[(int) (3.1 * fabs(sin (2.0*PI*sqrt(29.067))))]

O-19 C Array Bounds are Not Checked #define DAYS_IN_WEEK 7 double 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-20 Technicalities An array is a collection of variables Each element can be used wherever a simple variable of that type is allowed. Assignment, expressions, input/output An entire array can’t be treated as a single variable in C Can’t assign or compare arrays using =, ==, <, … Can’t use scanf or printf to read or write an entire array But, you can do these things one element at a time.

O-21 “Parallel” Arrays A 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 scores

O-22 Parallel Arrays Example Suppose we have a midterm grade, final exam grade, and average score for each student. #define MT_WEIGHT0.30 #define FINAL_WEIGHT0.70 #define MAX_STUDENTS200 intnum_student, midterm[MAX_STUDENTS], final[MAX_STUDENTS] ; doublescore[MAX_STUDENTS] ;

O-23 Parallel 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 weighted average of exams in array score. */ for ( i = 0 ; i < num_student ; i = i + 1 ) { score[i] = MT_WEIGHT * midterm[i] + FINAL_WEIGHT * final[i] ; }

O-24 Array Elements as Parameters Individual array elements can be used as parameters, just like other simple variables. Examples: printf( “Last two are %f, %f”, rain[5], rain[6] ) ; draw_house( color[i], x[i], y[i], windows[i] ) ; scanf( “%lf”, &rain[0] ) ; swap( &rain[i], &rain[i+1] ) ;

O-25 Whole Arrays as Parameters Array parameters (entire arrays) work differently: An array is never copied (no call by value) The array name is always treated as a pointer parameter The & and * operators are not used Programming issue: in C, arrays do not contain information about their size, so the size often needs to be passed as an additional parameter.

O-26 Array Parameter Example #define ARRAY_SIZE 200 double average ( int a[ARRAY_SIZE] ) { int i, total = 0 ; for ( i = 0 ; i < ARRAY_SIZE ; i = i + 1 ) total = total + a[i] ; return ((double) total / (double) ARRAY_SIZE) ; } int x[ARRAY_SIZE] ;... x_avg = average ( x ) ;

O-27 Picture #define ARRAY_SIZE 200 double average ( int a[ARRAY_SIZE] ) { int i, total = 0 ; for ( i = 0 ; i < ARRAY_SIZE ; i = i + 1 ) total = total + a[i] ; return ((double) total / (double) ARRAY_SIZE) ; } int x[ARRAY_SIZE] ;... x_avg = average ( x ) ;

O-28 Picture #define ARRAY_SIZE 200 double average ( int a[ARRAY_SIZE] ) { int i, total = 0 ; for ( i = 0 ; i < ARRAY_SIZE ; i = i + 1 ) total = total + a[i] ; return ((double) total / (double) ARRAY_SIZE) ; } int x[ARRAY_SIZE] ;... x_avg = average ( x ) ; caller x

O-29 Picture #define ARRAY_SIZE 200 double average ( int a[ARRAY_SIZE] ) { int i, total = 0 ; for ( i = 0 ; i < ARRAY_SIZE ; i = i + 1 ) total = total + a[i] ; return ((double) total / (double) ARRAY_SIZE) ; } int x[ARRAY_SIZE] ;... x_avg = average ( x ) ; caller x average a i total

O-30 Picture #define ARRAY_SIZE 200 double average ( int a[ARRAY_SIZE] ) { int i, total = 0 ; for ( i = 0 ; i < ARRAY_SIZE ; i = i + 1 ) total = total + a[i] ; return ((double) total / (double) ARRAY_SIZE) ; } int x[ARRAY_SIZE] ;... x_avg = average ( x ) ; caller x average a i total

O-31 /* Set vsum to sum of vectors a and b. */ void VectorSum( int a[3], int b[3], int vsum[3]) { int i ; for ( i = 0 ; i < 3 ; i = i + 1 ) vsum[i] = a[i] + b[i] ; } int main(void) { int x[3] = {1,2,3}, y[3] = {4,5,6}, z[3] ; VectorSum( x, y, z ); printf( “%d %d %d”, z[0], z[1], z[2] ) ; } Vector Sum Example note: no * no &

O-32 Usually the size is omitted in an array parameter declaration. /* sum the vectors of the given length */ void VectorSum( int a[ ], int b[ ], int vsum[ ], int length) { int i ; for ( i = 0 ; i < length ; i = i + 1 ) vsum[i] = a[i] + b[i] ; } int x[3] = {1,2,3}, y[3] = {4,5,6}, z[3] ; VectorSum( x, y, z, 3 ); General Vector Sum

O-33 Bonus Topic: Initializing Arrays Review: "Initialization" means giving something a value for the first time. General rule: variables have to be initialized before their value is used. Review: Various ways of initializing assignment statement scanf (or other function call using &) initializer when declaring parameters (initialized with argument values)

O-34 Array Initializers int w[4] = {1, 2, 30, -4}; /*w has size 4, all 4 are initialized */ char vowels[6] = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}, /*vowels has size 6, only 5 have initializers */ /* vowels[5] is uninitialized */

O-35 Array Initializers int w[4] = {1, 2, 30, -4}; /*w has size 4, all 4 are initialized */ char vowels[6] = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}, /*vowels has size 6, only 5 have initializers */ /* vowels[5] is uninitialized */ Caution: cannot use this notation in assignment statement: w = {1, 2, 30, -4}; /*SYNTAX ERROR */

O-36 Incomplete Array Size double x[ ] = {1.0, 3.0, -15.0, 7.0, 9.0}; /*x has size 5, all 5 are initialized */ But: double x[ ]; /* ILLEGAL */

O-37 Summary Arrays hold multiple values All values are of the same type Notation: [i ] selects one array element [0] is always the first element C does not check array bounds! Especially useful with large amounts of data Often processed within loops Entire array can be passed as a parameter