Alternate Version of Starting Out with C++, Third Edition

Slides:



Advertisements
Similar presentations
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Advertisements

Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 8 Arrays.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
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.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
A First Book of ANSI C Fourth Edition
Chapter 8 Arrays and Strings
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
Arrays Chapter 8.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by.
A First Book of ANSI C Fourth Edition Chapter 8 Arrays.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C-Strings, Arrays, and String Class Review.
Lecture: Arrays. 7.1 Arrays Hold Multiple Values.
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.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by.
+ Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 8 Arrays.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 7 Arrays.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 8: Arrays by Tony.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays.
Chapter 7 Arrays Csc 125 Introduction to C++. Topics Arrays Hold Multiple Values Array Operations Arrays as function arguments Two-dimensional arrays.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 7: Arrays.
Arrays Chapter 7. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1.
Lecture 8 – Array (Part 1) FTMK, UTeM – Sem /2014.
Copyright © 2012 Pearson Education, Inc. Chapter 7: Arrays.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
ARRAYS (C) KHAERONI, M.SI. OVERVIEW Introduction to Arrays Arrays in Functions Programming with Arrays Multidimensional Arrays.
Chapter 7: Arrays. 7.1 Arrays Hold Multiple Values.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arrays Hold Multiple Values 7.1.
Lecture 2 Arrays. Topics 1 Arrays hold Multiple Values 2 Accessing Array Elements 3 Inputting and Displaying Array Contents 4 Array Initialization 5 Using.
Chapter 8: Arrays. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Chapter 7: Arrays.
Lecture 6 Arrays and Vectors
Chapter 7: Arrays.
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
© 2016 Pearson Education, Ltd. All rights reserved.
Lecture 3 C & C++ programming.
New Structure Recall “average.cpp” program
CNG 140 C Programming (Lecture set 10)
Chapter 7: Arrays.
7 Chapter Arrays.
Chapter 8: Arrays Starting Out with C++ Early Objects Eighth Edition
7 Arrays.
CNG 140 C Programming (Lecture set 8)
Standard Version of Starting Out with C++, 4th Edition
Objectives You should be able to describe: Addresses and Pointers
7 Arrays.
Arrays Arrays A few types Structures of related data items
Standard Version of Starting Out with C++, 4th Edition
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Presentation transcript:

Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays Copyright 2003 Scott/Jones Publishing

Topics 8.1 Arrays Hold Multiple Values 8.2 Accessing Array Elements 8.3 Inputting and Displaying Array Contents 8.4 Array Initialization 8.5 Processing Array Contents 8.6 Using Parallel Arrays Chapter 8 slide 2

Topics 8.7 The typedef Statement 8.8 Arrays as Function Arguments 8.9 Two-Dimensional Arrays 8.10 Vectors 8.13 Arrays of Structures 8.14 Arrays of Class Objects Chapter 8 slide 3

8.1 Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations Declared using [] operator: int tests[5]; Chapter 8 slide 4

Array - Memory Layout The definition: allocates the following memory: int tests[5]; allocates the following memory: first element second element third element fourth element fifth element Chapter 8 slide 5

Array Terminology In the definition int tests[5]; int is the data type of the array elements tests is the name of the array 5, in [5], is the size declarator. It shows the number of elements in the array. The size of an array is (number of elements) * (size of each element) Chapter 8 slide 6

Array Terminology The size of an array is: Examples: the total number of bytes allocated for it (number of elements) * (number of bytes for each element) Examples: int tests[5] is an array of 20 bytes, assuming 4 bytes for an int long double measures[10]is an array of 80 bytes, assuming 8 bytes for a long double Chapter 8 slide 7

8.2 Accessing Array Elements Each array element has a subscript, used to access the element. Subscripts start at 0 subscripts: 1 2 3 4 Chapter 8 slide 8

Accessing Array Elements Array elements can be used as regular variables: tests[0] = 79; cout << tests[0]; cin >> tests[1]; tests[4] = tests[0] + tests[1]; Arrays must be accessed via individual elements: cout << tests; // not legal Chapter 8 slide 9

Global vs. Local Array Global array  all elements initialized to 0 or NULL Local array  all elements uninitialized by default Chapter 8 slide 10

8.3 Inputting and Displaying Array Contents Array elements can be used with cin, cout If array represents a C-string or C++ string object, can read in or display using just array name: char name[10]; // or 'string name;' cin >> name; cout << name << endl; Arrays of other types: element-by-element pr8-01.cpp Chapter 8 slide 11

Inputting and Displaying Array Contents Can access element with constant subscript: cout << tests[3] << endl; Can use integer expression as subscript: for (i = 0; i < 5;i++) cout << tests[i] << endl; No checks that subscript is in range – program may overwrite other memory pr8-02.cpp, pr8-03.cpp, pr8-04.cpp Chapter 8 slide 12

8.4 Array Initialization Can be initialized during program execution with assignment statements: tests[0] = 79; tests[1] = 82; // etc. Can be initialized at array definition with an initialization list: int tests[5] = {79,82,91,77,84}; pr8-05.cpp, pr8-06.cpp, pr8-07.cpp Chapter 8 slide 13

Partial Array Initialization If array is initialized at definition with fewer initial values than the size declarator of the array, the remaining elements will be set to 0 or NULL: int tests[5] = {79, 82}; Initial values used in order; cannot skip over elements to initialize noncontiguous range 79 82 pr8-08.cpp Chapter 8 slide 14

Implicit Array Sizing Can determine array size by the size of the initialization list: short quizzes[]={12,17,15,11}; Must use either array size declarator or initialization list at array definition 12 17 15 11 Chapter 8 slide 15

8.5 Processing Array Contents Array elements can be treated as ordinary variables of the same type as the array When using ++, -- operators, don’t confuse the element with the subscript: tests[i]++; // add 1 to tests[i] tests[i++]; // increment i, no // effect on tests pr8-09.cpp Chapter 8 slide 16

Sum of Array Elements Use a simple loop to add together array elements: int tnum; float average, sum = 0; for(tnum = 0; tnum < 5; tnum++) sum += tests[tnum]; Once summed, can compute average: average = sum/5; pr8-10.cpp, pr8-11.cpp Chapter 8 slide 17

Strings Can be processed using array name (entire string at once) or using subscripts(element at a time): string city; cout << "Enter city name: "; cin >> city; pr8-12.cpp 'S' 'a' 'l' 'e' 'm' city[0] city[1] city[2] city[3] city[4] Chapter 8 slide 18

8.6 Using Parallel Arrays Parallel arrays: two or more arrays that contain related data Subscript is used to relate arrays: elements at same subscript are related Arrays may be of different types pr8-13.cpp Chapter 8 slide 19

Parallel Array Example string name[5]; // student name float average[5];// course average char grade[5]; // course grade ... for(int i = 0; i < 5; i++) cout << "Student: " << name[i] << " average: " << average[i] << " grade: " << grade[i] << endl; Chapter 8 slide 20

8.7 The typedef Statement Creates an alias for a simple or structured data type Format: typedef <existing type> <new name>; Example: typedef unsigned int uint; uint tests[5]; // array of unsigned // ints Chapter 8 slide 21

Uses of typedef Used to make code more readable Can be used to create alias for array of a particular type: typedef int program[8]; // program now names a data type // that is an array of 8 ints program prog1, prog2;// 2 arrays Chapter 8 slide 22

8.8 Arrays as Function Arguments To pass an array to a function, just use the array name: showScores(tests); To define a function that takes an array parameter, use empty [] for array argument: void showScores(int []); // function prototype void showScores(int tests[]) // function header pr8-14.cpp, pr8-15.cpp, pr8-16.cpp, pr8-17.cpp Chapter 8 slide 23

Arrays as Function Arguments When passing an array to a function, it is common to pass array size so that function knows how many elements to process: showScores(tests, 5); Array size must also be reflected in prototype, header: void showScores(int [], int); // function prototype void showScores(int tests[], int size) // function header Chapter 8 slide 24

Arrays as Function Arguments Can use typedef to simplify function prototype, heading: typedef int intArray[]; // typedef void showScores(intArray, int); // function prototype void showScores(intArray tests, int size) // function header Chapter 8 slide 25

Modifying Arrays in Functions Array names in functions are similar to reference variables – changes made to array in a function are reflected in actual array in calling function Need to exercise caution that array is not inadvertantly changed by a function pr8-18.cpp Chapter 8 slide 26

8.9 Two-Dimensional Arrays Can define one array for multiple sets of data Like a table in a spreadsheet Use two size declarators in definition: int exams[4][3]; First declarator is number of rows; second is number of columns Chapter 8 slide 27

Two-Dimensional Array Representation int exams[4][3]; Use two subscripts to access element: exams[2][2] = 86; columns exams[0][0] exams[0][1] exams[0][2] exams[1][0] exams[1][1] exams[1][2] exams[2][0] exams[2][1] exams[2][2] exams[3][0] exams[3][1] exams[3][2] r o w s pr8-19.cpp Chapter 8 slide 28

Initialization at Definition Two-dimensional arrays are initialized row-by-row: int exams[2][2] = { {84, 78}, {92, 97} }; Can omit inner { }, some initial values in row – array elements without initial values will be set to 0 or NULL 84 78 92 97 Chapter 8 slide 29

Two-Dimensional Array as Parameter, Argument Use array name as argument in function call: getExams(exams, 2); Use empty [] for row, size declarator for column in prototype, header: void getExams(int [][2], int); // prototype void getExams(int exams[][2], int rows) // header pr8-20.cpp Chapter 8 slide 30

Two-Dimensional Array as Parameter, Argument Can use typedef for simpler notation: typedef int intExams[][2]; ... void getExams(intExams, int); // prototype void getExams(intExams exams, int rows) // header pr8-21.cpp Chapter 8 slide 31

Multi-Dimensional Arrays Can define arrays with any number of dimensions: short rectSolid(2,3,5); float timeGrid(3,4,3,4); When used as parameter, specify all but 1st dimension: void getRectSolid(short [][3][5]); pr8-22.cpp Chapter 8 slide 32

8.10 Vectors Defined in the Standard Template Library (Chapter 15) Can hold values of any type: vector<int> scores; Automatically adds space as more is needed – no need to determine size at definition Can use [] to access elements pr8-23.cpp Chapter 8 slide 33

Declaring Vectors Vectors require vector header file Declare a vector: vector<int> scores; Declare a vector with initial size 30: vector<int> scores(30); Declare a vector and initialize all elements to 0: vector<int> scores(20, 0); Declare a vector initialized to size and contents of another vector: vector<int> scores(finals); Chapter 8 slide 34

Growing a Vector’s Size Use size member function to determine size of a vector: howbig = scores.size(); Use push_back member function to add element to a full array or to an array that had no defined size: scores.push_back(75); pr8-24.cpp, pr8-25.cpp Chapter 8 slide 35

Removing Vector Elements Use pop_back member function to remove last element from vector: scores.pop_back(); To remove all contents of vector, use clear member function: scores.clear(); To determine if vector is empty, use empty member function: while (!scores.empty()) ... pr8-26.cpp, pr8-27.cpp, pr8-28.cpp Chapter 8 slide 36

8.13 Arrays of Structures Structures can be used as array elements: struct Student { int studentID; string name; short yearInSchool; float gpa; }; Student class[30]; pr8-31.cpp Chapter 8 slide 37

Arrays of Structures Use array subscript to access a specific structure in the array Then, use dot operator to access members of structure: cin >> class[25].studentID; cout << class[i].name << "has GPA " << class[i].gpa << endl; Chapter 8 slide 38

8.14 Arrays of Class Objects Classes can also be used as array elements: class square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; square shapes[10]; pr8-32.cpp Chapter 8 slide 39

Arrays of Class Objects Use subscript to access a specific object in an object the array Use dot operator to access member functions of that object: shapes[4].setSide(12); for (i=0; i<10; i++) cout << shapes[i].getSide(); pr8-33.cpp Chapter 8 slide 40

Initialize Array of Objects Can use default constructor to perform same initialization for all objects Can use initialization list to supply specific initial values of objects: Square shapes[5] = {1,2,3,4,5}; Default constructor used for remaining objects if initialization list is too short Must call constructor in initialization list if it takes > 1 argument pr8-34.cpp, pr8-35.cpp Chapter 8 slide 41

Initialize Array of Objects If class has constructor that takes > 1 argument, then initialization list must include a call to the constructor: Rectangle spaces[3] = { Rectangle(2,5), Rectangle(1,3), Rectangle(7,7) }; Chapter 8 slide 42

Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays Copyright 2003 Scott/Jones Publishing

Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common Programming Errors A First Book of C++: From Here To There, Third Edition

One-Dimension Arrays One-Dimension Array(Single-Dimension Array or Vector): a list of related values All items in list have same data type All list members stored using single group name Example: a list of grades 98, 87, 92, 79, 85 All grades are integers and must be declared Can be declared as single unit under a common name (the array name) A First Book of C++: From Here To There, Third Edition

One-Dimension Arrays (continued) Array declaration statement provides: The array(list) name The data type of array items The number of items in array Syntax dataType arrayName[numberOfItems] Common programming practice requires defining number of array items as a constant before declaring the array A First Book of C++: From Here To There, Third Edition

One-Dimension Arrays (continued) Examples of array declaration statements: const int NUMELS = 5; // define a constant // for the number of // items int grade[NUMELS]; // declare the array const int ARRAYSIZE = 4; char code[ARRAYSIZE]; const int NUMELS = 6; double prices[NUMELS]; A First Book of C++: From Here To There, Third Edition

One-Dimension Arrays (continued) Each array allocates sufficient memory to hold the number of data items given in declaration Array element(component): an item of the array Individual array elements stored sequentially A key feature of arrays that provides a simple mechanism for easily locating single elements A First Book of C++: From Here To There, Third Edition

One-Dimension Arrays (continued) A First Book of C++: From Here To There, Third Edition

One-Dimension Arrays (continued) Index (subscript value): position of individual element in an array Accessing of array elements: done by giving array name and element’s index grade[0] refers to first grade stored in grade array Subscripted variables can be used anywhere that scalar variables are valid: grade[0] = 95.75; grade[1] = grade[0] - 11.0; A First Book of C++: From Here To There, Third Edition

One-Dimension Arrays (continued) A First Book of C++: From Here To There, Third Edition

One-Dimension Arrays (continued) Subscripts: do not have to be integers Any expression that evaluates to an integer may be used as a subscript Subscript must be within the declared range Examples of valid subscripted variables (assumes i and j are int variables): grade[i] grade[2*i] grade[j-i] A First Book of C++: From Here To There, Third Edition

Input and Output of Array Values Individual array elements can be assigned values interactively using a cin stream object cin >> grade[0]; cin >> grade[1] >> grade[2] >> grade[3]; cin >> grade[4] >> prices[6]; Instead, a for loop can be used const int NUMELS = 5; for (int i = 0; i < NUMELS; i++) { cout << "Enter a grade: "; cin >> grade[i]; } A First Book of C++: From Here To There, Third Edition

Input and Output of Array Values (continued) Bounds checking: C++ does not check if value of an index is within declared bounds If an out-of-bounds index is used, C++ will not provide notification Program will attempt to access out-of-bounds element, causing program error or crash Using symbolic constants helps avoid this problem A First Book of C++: From Here To There, Third Edition

Input and Output of Array Values (continued) Using cout to display subscripted variables: Example 1 cout << prices[5]; Example 2 cout << "The value of element " << i << " is " << grade[i]; Example 3 const int NUMELS = 20; for (int k = 5; k < NUMELS; k++) cout << k << " " << amount[k]; A First Book of C++: From Here To There, Third Edition

Input and Output of Array Values (continued) Program example of array I/O (program 8.1): #include <iostream> using namespace std; int main() { const int NUMELS = 5; int i, grade[NUMELS]; for (i = 0; i < NUMELS; i++) // Enter the grades cout << "Enter a grade: "; cin >> grade[i]; } cout << endl; for (i = 0; i < NUMELS; i++) // Print the grades cout << "grade [" << i << "] is " << grade[i] << endl; return 0; A First Book of C++: From Here To There, Third Edition

Input and Output of Array Values (continued) Sample run using Program 8.1: Enter a grade: 85 Enter a grade: 90 Enter a grade: 78 Enter a grade: 75 Enter a grade: 92 grade[0] is 85 grade[1] is 90 grade[2] is 78 grade[3] is 75 grade[4] is 92 A First Book of C++: From Here To There, Third Edition

Array Initialization Array elements can be initialized within declaration statements Initializing elements must be included in braces Example: const int NUMGALS = 20; int gallons[NUMGALS] = {19, 16, 14, 19, 20, 18, // initializing values 12, 10, 22, 15, 18, 17, // may extend across 16, 14, 23, 19, 15, 18, // multiple lines 21, 5}; A First Book of C++: From Here To There, Third Edition

Array Initialization (continued) Size of array may be omitted when initializing values are included in declaration statement Example: the following are equivalent const int NUMCODES = 6; char code[6] = {'s', 'a', 'm', 'p', 'l', 'e'}; char code[ ] = {'s', 'a', 'm', 'p', 'l', 'e'}; Both declarations set aside 6 character locations for an array named code A First Book of C++: From Here To There, Third Edition

Array Initialization (continued) Simplified method for initializing character arrays char code[ ] = “sample”; //no braces or commas This statement uses the string “sample” to initialize the code array The array is comprised of 7 characters The first 6 characters are the letters: s, a, m, p, l, e The last character (the escape sequence \0) is called the Null character A First Book of C++: From Here To There, Third Edition

Array Initialization (continued) A First Book of C++: From Here To There, Third Edition

Arrays as Arguments Array elements are passed to a called function in same manner as individual scalar variables Example: findMax(grades[2], grades[6]); Passing a complete array to a function provides access to the actual array, not a copy Making copies of large arrays is wasteful of storage A First Book of C++: From Here To There, Third Edition

Arrays as Arguments (continued) Examples of function calls that pass arrays int nums[5]; // an array of five integers char keys[256]; // an array of 256 characters double units[500], grades[500];// two arrays of 500 //doubles The following function calls can then be made: findMax(nums); findCharacter(keys); calcTotal(nums, units, grades); A First Book of C++: From Here To There, Third Edition

Arrays as Arguments (continued) Suitable receiving side function header lines: int findMax(int vals[5]) char findCharacter(char inKeys[256]) void calcTotal(int arr1[5], double arr2[500], double arr3[500]) A First Book of C++: From Here To There, Third Edition

Arrays as Arguments (continued) Example of passing arrays as arguments (program 8.4): Constant MAXELS is declared globally Prototype for findMax() uses constant MAXELS to declare that findMax() expects an array of five integers as an argument As shown in Figure 8.7,only one array is created in Program 8.4 In main() the array is known as nums In findMax() it is known as vals A First Book of C++: From Here To There, Third Edition

Arrays as Arguments (continued) Example: Program 8.4 #include <iostream> using namespace std; const int MAXELS = 5; int findMax(int [MAXELS]); // function prototype int main() { int nums[MAXELS] = {2, 18, 1, 27, 16}; cout << "The maximum value is " << findMax(nums) << endl; return 0; } // find the maximum value int findMax(int vals[MAXELS]) int i, max = vals[0]; for (i = 1; i < MAXELS; i++) if (max < vals[i]) max = vals[i]; return max; A First Book of C++: From Here To There, Third Edition

Arrays as Arguments (continued) A First Book of C++: From Here To There, Third Edition

Two-Dimensional Arrays Two-dimensional array (table): consists of both rows and columns of elements Example: two-dimensional array of integers 8 16 9 52 3 15 27 6 25 2 10 Array declaration: names the array val and reserves storage for it int val[3][4]; A First Book of C++: From Here To There, Third Edition

Two-Dimensional Arrays (continued) Locating array elements (Figure 8.9) val[1][3] uniquely identifies element in row 1, column 3 Examples using elements of val array: price = val[2][3]; val[0][0] = 62; newnum = 4 * (val[1][0] - 5); sumRow = val[0][0] + val[0][1] + val[0][2] + val[0][3]; The last statement adds the elements in row 0 and sum is stored in sumRow A First Book of C++: From Here To There, Third Edition

Two-Dimensional Arrays (continued) A First Book of C++: From Here To There, Third Edition

Two-Dimensional Arrays (continued) Initialization: can be done within declaration statements (as with single-dimension arrays) Example: int val[3][4] = { {8,16,9,52}, {3,15,27,6}, {14,25,2,10} }; First set of internal braces contains values for row 0, second set for row 1, and third set for row 2 Commas in initialization braces are required; inner braces can be omitted A First Book of C++: From Here To There, Third Edition

Two-Dimensional Arrays (continued) Processing two-dimensional arrays: nested for loops typically used Easy to cycle through each array element A pass through outer loop corresponds to a row A pass through inner loop corresponds to a column Nested for loop in Program 8.7 used to multiply each val element by 10 and display results Output of Program 8.7 Display of multiplied elements 80 160 90 520 30 150 270 60 140 250 20 100 A First Book of C++: From Here To There, Third Edition

Two-Dimensional Arrays (continued) Prototypes for functions that pass two-dimensional arrays can omit the row size of the array Example (program 8.8): Display (int nums[ ][4]); Row size is optional but column size is required The element val[1][3] is located 28 bytes from the start of the array (assuming 4 bytes for an int) A First Book of C++: From Here To There, Third Edition

Two-Dimensional Arrays (continued) Determining offset of an array Computer uses row index, column index and column size to determine offset as shown below and in Figure 8.11 A First Book of C++: From Here To There, Third Edition

Two-Dimensional Arrays (continued) A First Book of C++: From Here To There, Third Edition

Larger-Dimension Arrays Arrays with more than two dimensions allowed in C++ but not commonly used Example: int response[4][10][6] First element is response[0][0][0] Last element is response[3][9][5] A three-dimensional array can be viewed as a book of data tables (Figure 8.12) First subscript (rank) is page number of table Second subscript is row in table Third subscript is desired column A First Book of C++: From Here To There, Third Edition

Larger-Dimension Arrays (continued) A First Book of C++: From Here To There, Third Edition

Common Programming Errors Forgetting to declare an array Results in a compiler error message equivalent to “invalid indirection” each time a subscripted variable is encountered within a program Using a subscript that references a nonexistent array element For example, declaring array to be of size 20 and using a subscript value of 25 Not detected by most C++ compilers and will probably cause a runtime error A First Book of C++: From Here To There, Third Edition

Common Programming Errors (continued) Not using a large enough counter value in a for loop counter to cycle through all array elements Forgetting to initialize array elements Don’t assume compiler does this A First Book of C++: From Here To There, Third Edition

Summary Single-dimensional array: a data structure that stores a list of values of same data type Must specify data type and array size int num[100]; creates an array of 100 integers Array elements are stored in contiguous locations in memory and referenced using the array name and a subscript For example, num[22] A First Book of C++: From Here To There, Third Edition

Summary (continued) Two-dimensional array is declared by listing both a row and column size with data type and name of array Arrays may be initialized when they are declared For two-dimensional arrays you list the initial values, in a row-by-row manner, within braces and separating them with commas Arrays are passed to a function by passing name of array as an argument A First Book of C++: From Here To There, Third Edition

Array [6] Chapter 8 slide 83

Array [5]+adding Chapter 8 slide 84

Array [7] and max number Chapter 8 slide 85

Adding 5 for each Chapter 8 slide 86

Multi dimensional array Chapter 8 slide 87

Printing matrix Chapter 8 slide 88

Adding two matrix Chapter 8 slide 89

Chapter 8 slide 90

Chapter 8 slide 91

Chapter 8 slide 92