Arrays
Arrays
Arrays
An
array is a collection of data elements that are of the same type (e.g., a collection of integers,characters, doubles) are like flats in a building, or post office boxes provide a good way to name a collection, and to reference its individual elements.
Arrays
Arrays
Array Applications
Given
a list of test scores, determine the maximum and minimum scores. Read in a list of student names and rearrange them in alphabetical order (sorting). Given the height measurements of students in a class, output the names of those students who are taller than average.
Array Declaration
Syntax:
<type> <arrayName>[<dimension>]
The
The
size of the array is indicated by <dimension>, the number of elements in the array <dimension> must be an int constant or a constant expression. Note that it is possible for an array to have multiple dimensions.
0 A --
1 --
2 --
3 --
4 --
5 --
6 --
7 --
8 --
9 --
Subscripting
Suppose
int A[10]; // array of 10 ints
Last element has an index one less than the size of the list
A[9]
Subscripting
// array of 10 uninitialized ints int A[10];
--
1
-7
--8 9
-- -- -1 -- -- -- -- -- -A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
Consider
int A[10], i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3; A[j+1] = A[i] + A[0]; A[A[j]] = 12; cin >> A[k]; // where the next input value is 3
1 -8 6 3 --5 12 -A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
Array Initialization
int A[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
0 A 9 1 8 2 7 3 6 4 5 5 4 6 3 7 2 8 1 9 0
Box A[3]
-1
A[3] = -1;
0 A 9 1 8 2 7 3 -1 4 5 5 4 6 3 7 2 8 1 9 0
Example Definitions
Suppose
const const const const int int int int N = 20; M = 40; MaxStringSize = 80; MaxListSize = 1000;
0 1 2
----
----
----
----
----
----
----
----
----
----
1 ----
4 ----
5 ----
6 ----
7 ----
8 ----
9 ----
0 1 2
----
-- -a --- --
Inputting a List
const int MaxSize = 10000; int A[MaxSize]; int n = 0; int CurrentInput; while(n< MaxSize && cin>>CurrentInput){ A[n] = CurrentInput; n++; }
Displaying a List
// List A of n elements has already been set
int i; for (i=0; i<n; i++) cout << A[i] << " "; cout << endl;
Smallest Value
Problem
Input
A list of integers and a value indicating the number of integers Smallest value in the list
List remains unchanged after finding the smallest value!
Output
Note
Idea
When looking for smallest value, need a way of remembering best candidate found so far
Design
a loop to consider each element in turn If current element is smallest so far, then update smallest value so far
When done examining all of the elements, the smallest value seen so far is the smallest value
Smallest Value
const int N=10; int A[N]; int SmallestValueSoFar, i; ... // A[] is input by user
SmallestValueSoFar = A[0]; for (i=1; i<N; i++) if (A[i] < SmallestValueSoFar) SmallestValueSoFar = A[i];