Chapter 6 Arrays ITP 134 C++ Study Guide Chapter 6 Arrays Instructions: Use this Study Guide to help you understand the important points of this chapter. See the book for lots of great programming examples. Important concepts, keywords, statements and functions are shown in emphasized font. Code syntax and examples are shown in code font. Games & Graphics in C++ 2nd edition by Tony Gaddis 6.1 Array Basics CONCEPT: An array allows you to store a group of items of the same data type together in memory. Processing a large of items in an array is usually easier than processing a large of items stored in separate variables. (pg 205) Arrays use a single variable name to store a group of values. Arrays are specifically designed to store and process data. (pg 205) Variables are a named memory location and can only hold one value at a time. (earlier chapters) Array Elements and Subscripts The storage locations in an array are known as elements. In memory, an array’s elements are located in consecutive memory locations. (pg 207) Each element in an array is assigned a unique number known as a subscript or index. In C++, the first subscript is 0. (pg 207) You must declare what datatype the array can store. Every element in the array has to be the same datatype such as int, float, bool etc. By Eaton For example, suppose you are writing a program to calculate the average of 5 numbers. Using variables you could write the following code snippet. int size, number0, number1, number2, number3, number4, sum, average; const SIZE = 5; // how many numbers are you averaging? number0 = 10; // numbers start at 10 and increment 10 number1 = 20; number2 = 30; number3 = 40; number5 = 50; sum = number0 + number1 + number2 + number3 + number4; average= sum / size; This doesn’t seem so bad, but suppose you had to average 20 numbers. You can easily see the limitations of using simple variables. Let’s rewrite this code using an array of 20 numbers and a for loop. const SIZE = 20; int number[size]; for (int i = 0; i < size; i++) { number[i]= 10*(number[i]+1); Sum += number[i]; } average = sum/size; ITP 134 – Mrs. Eaton Chapter 6 Study Guide – 2nd Edition Page 1 Chapter 6 Arrays See Program 6-8 AverageArray.cpp (pg 224) for another code example of averaging numbers. the array. (pg 216) See Figure 6-4 Sequential search logic for a flowchart of this process. See Figure 6-2 for a visual example of values stored in an array. (pg 208) Searching a String Array Program 6-4 StringSearch.cpp demonstrates how to use the sequential search algorithm to find a target number in an array. (pg 219) Inputting and Outputting Array Contents You can read values from the keyboard and store in array just as a regular variable. You can also print the contents of an array element. (pg 208) Array Initialization Shortcut: You can initialize an array when you declare it. Here is an example (pg 209): const int SIZE = 5; int numbers[SIZE} = { 10, 20, 30, 40, 50 }; Using a Loop to Step through an Array Video Note (pg 210) See the code snippet for another example of using a for loop with an array . Also see my example on page 1 of this study guide. No Array Bounds Checking in C++ The C++ language does not check to see if you are out of bounds for the subscripts of any arrays that you create. You need to be sure to remember that the array subscripts start at 0 and the last subscript is always one less than the number of items that the array can hold. You will get an “out of bounds” error message or your program will crash if your program has this logic error. (pg 213) Watch for Off-by One Errors A common mistake is off-by-one-error. Since humans count from 1 instead of 0 it is easy to do. You need to be sure to remember that the array subscripts start at 0 and the last subscript is always one less than the number of items that the array can hold. (pg 213) Processing the Elements of an Array You can use the elements in an array for processing with mathematical expressions just as you can with variables. See In The Spotlight: Using Array Elements in a Math Expression for an example. (pg 214 – 215) 6.2 Sequentially Searching an Array CONCEPT: The sequential search algorithm is a simple technique for finding an item in an array. It steps through the array, beginning at the first element, and compares each element to the target item. The search stops when the element is found or reach the end of ITP 134 – Mrs. Eaton 6.3 Processing the Contents of an Array Copying an Array You can copy the contents of one array to another using a loop. For example: (pg 221) const int SIZE = 5; int numbers1[SIZE} = {100, 200, 300, 400, 500); int numbers2[SIZE]; //copy values from numbers1 array into //numbers2 array for (int i=0; i < SIZE; i++) { numbers2[i] = numbers1[i]; } Implicit Array Sizing In C++, you can declare an array and initialize an array without specifying its size. (pg 484) For example: int numbers[ ] = { 2, 4, 6, 8, 10 }; // array will be size 5 Comparing Arrays If you need to compare two arrays to see if they are equivalent, then you need to use a loop that goes through all the elements and compares each value for both arrays. See the code snippet example (pg 221). Totaling the Values in an Array To total the values in a numeric array, you use a loop with an accumulator variable. See Program 6-7 TotalArray.cpp for an example. (pg 223) Averaging the Values in an Array To calculate the average of the values in a numeric array, the first step is to use a loop with an accumulator variable. The second step is to divide the sum by the number of elements in the array. See Program 6-8 AverageArray.cpp for an example. (pg 224) Chapter 6 Study Guide – 2nd Edition Page 2 Chapter 6 Arrays Finding the Highest and Lowest Values in an Array To find the highest value in an array, create a variable to hold the highest value. Then assign the value in array[0] to this variable. Loop through the array element to compare the next value to the current highest element. See Figure 6-5 for a flowchart example to find the highest value. (pg 225) See Program 6-9 HighestElement.cpp for an example. (pg 226) See Figure 6-6 for a flowchart example to find the lowest value (pg 227) See Program 6-10 LowestElement.cpp for an example. (pg 227-228) Passing an Array as an Argument to a Function You can pass an entire array as an argument to a function, which give you the ability to modularize many of the operations you can perform with an array. Typically you pass the array and then the size of the array. See Program 6-11 ArrayArgument.cpp for an example. (pg 229) Partially Filled Arrays Sometimes you need to store a series of items in an array, but you do not know the exact number of items. One solution is to make the array large enough to hold the largest possible number of items. If you only partially fill an array you need to keep track of how many items are currently stored in the array so you do not try to process an empty item in the array. (pg 230) See Program 6-12 PartiallyFilledArray.cpp for an example. (pg 231-232) From CSC 200 Intro to CS class CONCEPT: A sorting algorithm rearranges the contents of an array so they appear in a specific order. The selection sort is a specific example of a sorting algorithm. 6.5 Two-Dimensional Arrays CONCEPT: A two-dimensional array is like several identical arrays put together. It is useful for storing multiple sets of data. Remember the subscripts are array[row][column] Passing Two-Dimensional Arrays to Functions When a two-dimensional array is passed to a function, the parameter type must contain a size declaratory for the number of columns in addition to the number of rows. See Program 6-16 Pass2dArray.cpp for an example. (pg 244-245) 6.6 Arrays of Three or More Dimensions CONCEPT: To model data that occurs in multiple sets (such as GPS data) most languages allow you to create arrays with multiple dimensions. See Figure 6-12 for a visual representation of a 3D array. (pg 246) Chapter 6 Program Examples 6.4 Parallel Arrays CONCEPT: By using the same subscript, you can establish relationships between data stored in two or more arrays. See Program 6-14 ParallelArrays.cpp for an example. (pg 238-239) ITP 134 – Mrs. Eaton See Program 6-15 TwoDimensionalArray.cpp for an example. (pg 242-243) Chapter 6 Study Guide – 2nd Edition Program 4-1 Comissions.cpp (pg 134-135) Program 6-1 ArrayInputOutput.cpp (pg 208-9) Program 6-2 ArrayLoop.cpp (pg 211-212) In the Spotlight: Program 6-3 CoffeShopPayroll.cpp (pg 214-215 ) Program 6-4 SequentialSearch.cpp (pg 218 ) Program 6-5 StringSearch.cpp (pg 219-220 ) Program 6-6 CompareArrays.cpp (pg 221-222 ) Program 6-7 TotalArray.cpp (pg 223 ) Program 6-8 AverageArray.cpp (pg 224 ) Program 6-9 HighestElement.cpp (pg 226) Program 6-10 LowestElement.cpp (pg 227-228 ) Program 6-11 ArrayArgument.cpp (pg 229) Program 6-12 PartiallyFilledArray .cpp (pg 231232 ) In the Spotlight:Program 6-13 main function (pg 233-234 ) Program 6-13 getTestScores function(pg 235) Program 6-13 getTotal function(pg 236) Program 6-13 getLowest function(pg 236) Program 6-14 ParallelArrays .cpp (pg 238-239 ) Program 6-15 TwoDimensionalArray .cpp (pg 242-243 ) Program 6-16 Pass2dArray .cpp (pg 244-245) Page 3