Copyright © 2002 Pearson Education, Inc. Slide 1.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 3-1 Concordia University Department of Computer Science and Software Engineering COMP345.
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.
Chapter 10.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
Chapter 9: Arrays and Strings
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
Lesson 7 Arrays CS 1 Lesson 7 -- John Cole1. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Chapter 7 Arrays. Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional Arrays.
Arrays One-Dimensional initialize & display Arrays as Arguments Part I.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Chapter 8 Arrays and Strings
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
C/C++ Basics (IV) Array, Pointers and Dynamic Arrays Berlin Chen 2003 Textbook: 1. Walter Savitch, “Absolute C++,” Addison Wesley, 2002 開發代理 2. Walter.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Static arrays.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 8 Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Arrays Dr. Jose Annunziato. Arrays Up to this point we have been working with individual primitive data types Arrays allow working with multiple instances.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
CSIS 113A Lecture 10 Arrays Glenn Stevenson CSIS 113A MSJC.
1 Understanding Arrays and Pointers COSC1567 C++ Programming Lecture 2.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
L what is a void-function? l what is a predicate? how can a predicate be used? l what is program stack? function frame? l what’s call-by-value? l what’s.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
L what is a void-function? l what is a boolean function? l is it possible for a function to have no parameters? l what is program stack? function frame?
Review 1.
Chapter 7 Arrays Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Computer Programming BCT 1113
Chapter 7 Arrays Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
New Structure Recall “average.cpp” program
Advanced Program Design with C++
Chapter 7 Arrays. Chapter 7 Arrays Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional.
7 Arrays.
Review of Everything Arrays
CMSC202 Computer Science II for Majors Lecture 03 – Arrays and Functions Dr. Katherine Gibson Based on slides by Chris Marron at UMBC.
7 Arrays.
Chapter 7 Arrays. Chapter 7 Arrays Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional.
Presentation transcript:

Copyright © 2002 Pearson Education, Inc. Slide 1

Copyright © 2002 Pearson Education, Inc. Slide 2 Chapter 5 Created by Frederick H. Colclough, Colorado Technical University Arrays

Copyright © 2002 Pearson Education, Inc. Slide 3 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory  Arrays in Functions  Arrays as function arguments, return values  Programming with Arrays  Partially Filled Arrays, searching, sorting  Multidimensional Arrays

Copyright © 2002 Pearson Education, Inc. Slide 4 Introduction to Arrays  Array definition:  A collection of data of same type  First ‘aggregate’ data type  Means ‘grouping’  int, float, double, char are simple data types  Used for lists of like items  Test scores, temperatures, names, etc.  Avoids declaring multiple simple variables  Can manipulate ‘list’ as one entity

Copyright © 2002 Pearson Education, Inc. Slide 5 Declaring Arrays  Declare the array  allocates memory int score[5];  Declares array of 5 integers named ‘score’  Similar to declaring five variables: int score[0], score[1], score[2], score[3], score[4]  Individual parts called many things:  Indexed or subscripted variables  ‘Elements’ of the array  Value in brackets called index or subscript  Numbered from 0 to size - 1

Copyright © 2002 Pearson Education, Inc. Slide 6 Accessing Arrays  Access using index/subscript  cout << score[3];  Note two uses of brackets:  In declaration, specifies SIZE of array  Anywhere else, specifies a subscript  Size, subscript need not be literal  int score[MAX_SCORES];  score[n+1] = 99;  If n is 2, identical to: score[3]

Copyright © 2002 Pearson Education, Inc. Slide 7 Array Usage  Powerful storage mechanism  Can issue command like:  “Do this to i th indexed variable” where i is computed by program  “Display all elements of array score”  “Fill elements of array score from user input”  “Find highest value in array score”  “Find lowest value in array score”

Copyright © 2002 Pearson Education, Inc. Slide 8 Array Program Example Display 5.1, page 174

Copyright © 2002 Pearson Education, Inc. Slide 9 for-loops with Arrays  Natural counting loop  Naturally works well ‘counting thru’ elements of an array  Example: for (idx = 0; idx<5; idx++) { cout << score[idx] << “off by “ << max – score[idx] << endl; }  Loop control variable (idx) counts from 0 – 5

Copyright © 2002 Pearson Education, Inc. Slide 10 Major Array Pitfall  Array indexes always start with zero!  Zero is ‘first’ number to computer scientists  C++ will ‘let’ you go beyond range  Unpredictable results  Compiler will not detect these errors!  Up to programmer to ‘stay in range’

Copyright © 2002 Pearson Education, Inc. Slide 11 Major Array Pitfall Example  Indexes range from 0 to (array_size – 1)  Example: double temperature[24]; // 24 is array size // Declares array of 24 double values called temperature  They are indexed as: temperature[0], temperature[1] … temperature[23]  Common mistake: temperature[24] = 5;  Index 24 is ‘out of range’!  No warning, possibly disastrous results

Copyright © 2002 Pearson Education, Inc. Slide 12 Memory override example with out-of- range index value #include int main() { int m = 99, n[4] = {11, 22, 33, 44}, i; for (i = 0; i < 4; i++) cout << "n[" << i << "] =" << n[i] << '\t' << "&n[" << i << "] =" << &n[i] << endl; cout << "m = " << m << "\t\t" << "&m = " << &m << endl; n[4] = 55; cout << "n[4] was not accounted for in the array declaration” << “ it overwrites content of variable m" << endl; cout << "n[4] = " << n[4] << '\t' << "&n[4] = " << &n[4] << endl; cout << "m = " << m << "\t\t" << "&m = " << &m << endl; return 0; }

Copyright © 2002 Pearson Education, Inc. Slide 13 Memory override example (The hexadecimal value 0x0012FF6C is the actual physical address of n[0] of a run on Microsoft Visual C where each integer variable is given 4 bytes in RAM)

Copyright © 2002 Pearson Education, Inc. Slide 14 Defined Constant as Array Size  Always use defined/named constant for array size  Example: const int NUMBER_OF_STUDENTS = 5; int score[NUMBER_OF_STUDENTS];  Improves readability  Improves versatility  Improves maintainability

Copyright © 2002 Pearson Education, Inc. Slide 15 Uses of Defined Constant  Use everywhere size of array is needed  In for-loop for traversal: for (idx = 0; idx < NUMBER_OF_STUDENTS; idx++) { // Manipulate array }  In calculations involving size: lastIndex = (NUMBER_OF_STUDENTS – 1);  When passing array to functions (later)  If size changes  requires only ONE change in program!

Copyright © 2002 Pearson Education, Inc. Slide 16 Arrays in Memory  Recall simple variables:  Allocated memory in an ‘address’  Array declarations allocate memory for entire array  Sequentially-allocated  Means addresses allocated ‘back-to-back’  Allows indexing calculations  Simple ‘addition’ from array beginning (index 0)

Copyright © 2002 Pearson Education, Inc. Slide 17 An Array in Memory Display 5.2, page 178

Copyright © 2002 Pearson Education, Inc. Slide 18 Initializing Arrays  As simple variables can be initialized at declaration: int price = 0;// 0 is initial value  Arrays can as well: int children[3] = {2, 12, 1};  Equivalent to following: int children[3]; children[0] = 2; children[1] = 12; children[2] = 1;

Copyright © 2002 Pearson Education, Inc. Slide 19 Auto-Initializing Arrays  If fewer values than size supplied:  Fills from beginning  Fills ‘rest’ with zero of array base type  If array-size is left out  Declares array with size required based on number of initialization values  Example: int b[] = {5, 12, 11};  Allocates array b to size 3

Copyright © 2002 Pearson Education, Inc. Slide 20 Arrays in Functions  As arguments to functions  Indexed variables  An individual ‘element’ of an array can be functin parameter  Entire arrays  All array elements can be passed as ‘one entity’  As return value from function  Can be done  chapter 10

Copyright © 2002 Pearson Education, Inc. Slide 21 Indexed Variables as Arguments  Indexed variable handled same as simple variable of array base type  Given this function declaration: void myFunction(double par1);  And these declarations: int i; double n, a[10];  Can make these function calls: myFunction(i);// i is converted to double myFunction(a[3]);// a[3] is double myFunction(n);// n is double

Copyright © 2002 Pearson Education, Inc. Slide 22 Subtlety of Indexing  Consider: myFunction(a[i]);  Value of i is determined first  It determines which indexed variable is sent myFunction(a[i*5]);  Perfectly legal, from compiler’s view  Programmer responsible for staying ‘in-bounds’ of array

Copyright © 2002 Pearson Education, Inc. Slide 23 Entire Arrays as Arguments  Formal parameter can be entire array  Argument then passed in function call is array name  Called ‘array parameter’  Send size of array as well  Typically done as second parameter  Simple int type formal parameter

Copyright © 2002 Pearson Education, Inc. Slide 24 Entire Array as Argument Example Display 5.3, page 183

Copyright © 2002 Pearson Education, Inc. Slide 25 Entire Array as Argument Example  Given previous example:  In some main() function definition, consider this calls: int score[5], numberOfScores = 5; fillup(score, numberOfScores);  1 st argument is entire array  2 nd argument is integer value  Note no brackets in array argument!

Copyright © 2002 Pearson Education, Inc. Slide 26 Array as Argument: How?  What’s really passed?  Think of array as 3 ‘pieces’  Address of first indexed variable (arrName[0])  Array base type  Size of array  Only 1 st piece is passed!  Just the beginning address of array  Very similar to ‘pass-by-reference’

Copyright © 2002 Pearson Education, Inc. Slide 27 Array Parameters  May seem strange  No brackets in array argument  Must send size separately  One nice property:  Can use SAME function to fill any size array!  Exemplifies ‘re-use’ properties of functions  Example: int score[5], time[10]; fillUp(score, 5); fillUp(time, 10);

Copyright © 2002 Pearson Education, Inc. Slide 28 The const Parameter Modifier  Recall: array parameter actually passes address of 1 st element  Similar to pass-by-reference  Function can then modify array!  Often desirable, sometimes not!  Protect array contents from modification  Use ‘const’ modifier before array parameter  Called ‘constant array parameter’  Tells compiler to ‘not allow’ modifications

Copyright © 2002 Pearson Education, Inc. Slide 29 Functions that Return an Array  Functions cannot return arrays same way simple types are returned  Requires use of a ‘pointer’  Will be discussed in chapter 10…

Copyright © 2002 Pearson Education, Inc. Slide 30 Programming with Arrays  Plenty of uses  Partially-filled arrays  Must be declared some ‘max size’  Sorting  Searching

Copyright © 2002 Pearson Education, Inc. Slide 31 Partially-filled Arrays  Difficult to know exact array size needed  Must declare to be largest possible size  Must then keep ‘track’ of valid data in array  Additional ‘tracking’ variable needed  int numberUsed;  Tracks current number of elements in array

Copyright © 2002 Pearson Education, Inc. Slide 32 Partially-filled Arrays Example Display 5.5, page 195

Copyright © 2002 Pearson Education, Inc. Slide 33 Global Constants vs. Parameters  Constants typically made ‘global’  Declared above main()  Functions then have scope to array size constant  No need to send as parameter then?  Technically yes  Why should we anyway?  Function definition might be in separate file  Function might be used by other programs!

Copyright © 2002 Pearson Education, Inc. Slide 34 Searching an Array  Very typical use of arrays  Display 5.6 next slide

Copyright © 2002 Pearson Education, Inc. Slide 35 Searching an Array Cont’d

Copyright © 2002 Pearson Education, Inc. Slide 36 Searching an Array Cont’d

Copyright © 2002 Pearson Education, Inc. Slide 37 Searching an Array Cont’d

Copyright © 2002 Pearson Education, Inc. Slide 38 Searching an Array Cont’d

Copyright © 2002 Pearson Education, Inc. Slide 39 Sorting an Array  Selection Sort Algorithm  E.W. Hu, CS240 S2003

Copyright © 2002 Pearson Education, Inc. Slide 40 Sorting an Array Example Display 5.8, page 201

Copyright © 2002 Pearson Education, Inc. Slide 41 Sorting an Array Example Cont’d

Copyright © 2002 Pearson Education, Inc. Slide 42 Sorting an Array Example Cont’d

Copyright © 2002 Pearson Education, Inc. Slide 43 Sorting an Array Example Cont’d Display 5.8, page 201

Copyright © 2002 Pearson Education, Inc. Slide 44 Multidimensional Arrays  Arrays with more than one index  char page[30][100];  Two indexes: An ‘array of arrays’  Visualize as: page[0][0], page[0][1], …, page[0][99] page[1][0], page[1][1], …, page[1][99] … page[29][0], page[29][1], …, page[29][99]  C++ allows any number of indexes  Typically no more than two

Copyright © 2002 Pearson Education, Inc. Slide 45 Multidimensional Array Parameters  Similar to one-dimensional array  1 st dimension size not given  Provided as second parameter  2 nd dimension size IS given  Example: void DisplayPage(const char p[][100], int sizeDimension1) { for (int index1=0; index1<sizeDimension1; index1++) { for (int index2=0; index2 < 100; index2++) cout << p[index1][index2]; cout << endl; } }

Copyright © 2002 Pearson Education, Inc. Slide 46 A 3 x 3 magic square int square[3][3] = {{8,1, 6}, {3, 5, 7}, {4, 9, 2}}  E.W. Hu, CS240 S2003

Copyright © 2002 Pearson Education, Inc. Slide 47 3x3 magic square example #include bool magic(int s[ ][3]); void displayArray(int [ ][3]); int main() { int s[3][3] = {{8, 1, 6}, {3, 5, 7}, {4, 9, 2}}; bool ans; displayArray(s); ans = magic(s); if (ans) cout << "\nThe square is magic!" << endl; else cout << "\nThe square is not magic!" << endl; return 0; }

Copyright © 2002 Pearson Education, Inc. Slide 48 3x3 magic square example continued void displayArray(int s[ ][3]) { int i, j; for (i = 0; i < 3; i++){ for (j = 0; j < 3; j++) cout << s[i][j] << '\t'; cout << endl; }

Copyright © 2002 Pearson Education, Inc. Slide 49 3x3 magic square example continued bool magic(int s[ ][3]) { int i, j, fdsum = 0, bdsum = 0, rsum, csum; // fdsum, bdsum are sums of forward & backward diagonals // rsum, csum are individual row and column sums for (i = 0; i<3; i++){ fdsum += s[i][i]; bdsum += s[i][3 - i - 1]; } if (fdsum != bdsum) return false; for (i = 0; i < 3; i++){ rsum = 0; csum = 0; for (j = 0; j < 3; j++){ rsum += s[i][j]; csum += s[j][i]; } if(rsum != fdsum || csum != fdsum) return false; else return true; }

Copyright © 2002 Pearson Education, Inc. Slide 50 Sort a list of names alphabetically #include #include // defines the strcmp and strcpy functions that are used in the program int fillArray(char name[ ][10]); void displayArray(char name[ ][10], int n); void sortArray(char name[ ][10], int n); void swap(char *s1, char *s2); int main() { char name[20][10];// assuming up to 20 names and each name contains up to 9 characters int n; n = fillArray(name);// pass the (constant) address of the 2-D array; same as &name[0][0] cout << "Name list before sort:\n"; displayArray(name, n); sortArray(name, n); cout << "Name list after sort:\n"; displayArray(name, n); return 0; }

Copyright © 2002 Pearson Education, Inc. Slide 51 Sort a list of names alphabetically continued int fillArray(char name[ ][10])// '10' is necessary { int n = 0, i = 0; char c = 'Y';// assume at least one name while(c == 'y' || c == 'Y') { cout << "Enter the name: "; cin >> name[i];// name[i] is the (constant) address of the ith row! n++; i++; cout << "More names to enter? press (Y/N) to continue/terminate: "; cin >> c; } return n; }

Copyright © 2002 Pearson Education, Inc. Slide 52 Sort a list of names alphabetically continued void displayArray(char name[ ][10], int n) { for (int i = 0; i < n; i++) cout << name[i] << '\t' << endl; // name[i] is the (constant) address of the ith row! return; }

Copyright © 2002 Pearson Education, Inc. Slide 53 Sort a list of names alphabetically continued void swap(char *s1, char *s2) { char hold[ ]; // char *hold; does not work strcpy(hold, s1); // It results in run time error: strcpy(s1, s2); // "the memory could not be written" strcpy(s2, hold); return; }

Copyright © 2002 Pearson Education, Inc. Slide 54 Sort a list of names alphabetically continued // bubble sort void sortArray(char name[ ][10], int n) { int pass, i, nc; // nc --- number of comparisons in each pass for (pass = 1; pass <= n - 1; pass++){ nc = n - pass - 1; // reduce # comparisons as pass # increases for (i = 0; i <= nc; i++) if (strcmp(name[i], name[i + 1]) > 0) swap(name[i], name[i + 1]); }

Copyright © 2002 Pearson Education, Inc. Slide 55 Row-wise mapping a 3x4 2-dimension array to 1-dimension physical memory space  E.W. Hu, CS240 S2003

Copyright © 2002 Pearson Education, Inc. Slide 56 Row-wise mapping a 4x3 2-dimension array to 1-dimension physical memory space  E.W. Hu, CS240 S2003

Copyright © 2002 Pearson Education, Inc. Slide 57 Summary 1  Array is collection of ‘same type’ data  Indexed variables of array used just like any other simple variables  for-loop ‘natural’ way to traverse arrays  Programmer responsible for staying ‘in bounds’ of array  Array parameter is ‘new’ kind  Similar to call-by-reference

Copyright © 2002 Pearson Education, Inc. Slide 58 Summary 2  Array elements stored sequentially  ‘Contiguous’ portion of memory  Only address of 1 st element is passed to functions  Partially-filled arrays  more tracking  Constant array parameters  Prevent modification of array contents  Multidimensional arrays  Create ‘array of arrays’