Beruflich Dokumente
Kultur Dokumente
Lecture 1
Topics
8-2
• Arrays Hold Multiple Values
8-3
Array Storage in Memory
The definition
int test[5];
allocates the following memory
8-4
Array Terminology
8-5
Array Terminology Examples
Examples:
8-6
• Accessing Array Elements
subscripts 0 1 2 3 4
8-7
Accessing Array Elements
8-9
Array Subscripts
8-10
Inputting and Displaying
All Array Elements
To access each element of an array
Use a (for) loop
The loop control variable sequence must be the
array valid subscripts, e.g., 0,1,2,…
A different array element will be referenced each
time through the loop
for (i = 0; i < 5; i++)
sum = sum + test[i];
8-11
No Bounds Checking WARNING!!
8-12
Off-By-One Errors
8-13
• Array Initialization
8-14
Partial Array Initialization
Initial
values used in order; cannot skip over
elements to initialize noncontiguous range
8-15
Implicit Array Sizing
8-16
• Processing Array Contents
Example:
if (principalAmt[3] >= 10000)
interest = principalAmt[3] * intRate1;
else
interest = principalAmt[3] * intRate2;
8-17
Using Increment and Decrement Operators
with Array Elements
int test[15];
When using ++ and -- operators, don’t
confuse the element with the subscript
test[i]++; // increments test[i], but has
// no effect on i.
test[i++]; // increments i, but has
// no effect on test array.
8-18
Copying One Array to Another
8-19
Are Two Arrays Equal?
string city;
cout << "Enter city name: ";
cin >> city;
'S' 'a' 'l' 'e' 'm'
city[0] city[1] city[2] city[3] city[4]
8-24
• 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
The
arrays do not have to hold data of the
same type
8-25
Parallel Array Example
Example:
8-28
Uses of typedef
8-29