COSC: Chap 10.1 Array concept
index
the element's location number in an array. arrayName[index]; -it enables direct access to any element -indicies start with 0 rather than 1
10.1.4: Arrays with element numbering starting with 0. Array scoresList has 10 elements with indices 0 to 9, accessed as scoresList[0] to scoresList[9]. 1. Assign the first element in scoresList with 77. 2. Assign the second element in scoresList with 77. 3. Assign the last element with 77. 4. If that array instead has 100 elements, what is the last element's index? 5. If the array's last index was 499, how many elements does the array have?
Solution: 1. scoresList[0] = 77; scoresList[0] refers to element number 0, which is the first element. 2. scoresList[1] = 77; When indices start at 0, the second element is at index 1. 3. scoresList[9] = 77; When indices start at 0, an N-element array's last element has index N - 1. With 10 elements, the last index is 9. 4. 99 The last index is at N - 1, where N is the number of elements, because the first element has index 0. 5. 500 Because numbering starts at 0, the last index is N - 1, where N is the number of elements.
10.1.3: Array basics. Array peoplePerDay has 365 elements, one for each day of the year. Valid accesses are peoplePerDay[0], [1], ..., [364]. 1. Which assigns element 0 with the value 250? 2. Which assigns element 1 with the value 99? 3. Given the following statements: peoplePerDay[9] = 5; peoplePerDay[8] = peoplePerDay[9] - 3; What is the value of peoplePerDay[8]? 4. Assume N is initially 1. Given the following: peoplePerDay[N] = 15; N = N + 1; peoplePerDay[N] = peoplePerDay[N - 1] * 3; What is the value of peoplePerDay[2]?
Solutions: 1. peoplePerDay[0] = 250 Assigns element 0 with 250. 2. peoplePerDay[1] = 99 Assigns element 1 with 99. 3. 2 peoplePerDay[9] is 5. So peoplePerDay[9] - 3 is 5 - 3, which is 2. 4. 45 peoplePerDay[1] is assigned with 15. Then, peoplePerDay[2] is assigned with peoplePerDay[1] * 3, which is 15 * 3, so 45.
element
each item in array
array
is a special variable having one name, but storing a list of data items, with each item directly accessible. -they enable direct access to elements
vector
some languages use these constructs, they are similar to an array