Sie sind auf Seite 1von 29

Arrays

Lecture 1
Topics

 Arrays Hold Multiple Values


 Accessing Array Elements
 Inputting and Displaying Array Contents
 Array Initialization
 Processing Array Contents
 Using Parallel Arrays
 The typedef Statement

8-2
• 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
const int ISIZE = 5;
int test[ISIZE]; … or int test[5];

8-3
Array Storage in Memory

The definition
int test[5];
allocates the following memory

Element 0 Element 1 Element 2 Element 3 Element 4

8-4
Array Terminology

In the definition int test[5];

 int is the data type of the array elements


 test is the name of the array
 [5] is the size declarator. It shows the maximum
number of elements in the array (i.e., array
capacity).
 The size of an array is the number of bytes
allocated for it
(number of elements) * (bytes needed for each
element)

8-5
Array Terminology Examples

Examples:

Assumes int uses 4 bytes and double uses 8 bytes


const int ISIZE = 5, DSIZE = 10;

int test[ISIZE]; // holds 5 ints, array


// occupies 20 bytes
double volumes[DSIZE];// holds 10 doubles
// array is 80 bytes

8-6
• Accessing Array Elements

 Each array element is a variable whose “name” contains


a subscript that uniquely identifies the element.
 Name of 3rd element array test is test[2].
 Subscripts start at 0

subscripts 0 1 2 3 4
8-7
Accessing Array Elements

Array elements are regular variables of


the base data type.
test
0 1 2 3 4
test[0] = 79;
cout << test[0];
cin >> test[1];
test[4] = test[0] + test[1];
cout << test; // shows address
8-8
• Inputting and Displaying
Array Contents

cout and cin can be used to display values


from and store values into an array
int test[5]; // 5-element array
cout << "Enter first test score ";
cin >> test[0];

8-9
Array Subscripts

 Array subscript can be an integer constant, integer


variable, or integer expression
 Examples (Subscript is):

cin >> test[3]; int constant

cout << test[i]; int variable

cout << test[i+j]; int expression

cin >> test[test[0]]; int expression

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!!

 C++ does not check that an array subscript is in


range
 An invalid array subscript can cause program to
overwrite other memory
 Example:
const int ISIZE = 3; num
int i = 4;
int num[ISIZE]; 25
num[i] = 25; [0] [1] [2]
 C++ Segmentation error!!

8-12
Off-By-One Errors

 Most often occur when a program


accesses data one position beyond the
end of an array, or misses the first or last
element of an array.
 Don’t confuse the ordinal number of an
array element (first, second, third) with
its subscript (0, 1, 2)

8-13
• Array Initialization

 Can be initialized during program execution with


assignment statements
test[0] = 79;
test[1] = 82; // etc.
 Can be initialized at array definition with an
initialization list
int test[5] = {79,82,91,77,84};

8-14
Partial Array Initialization

 Ifarray is initialized at definition with fewer values


than the size declarator of the array, remaining
elements will be set to 0 or NULL

int test[5] = {79, 82};


79 82 0 0 0

 Initial
values used in order; cannot skip over
elements to initialize noncontiguous range
8-15
Implicit Array Sizing

 Can determine array size by the size of


the initialization list
short quizzes[]={12,17,15,11};
12 17 15 11

 Must use either array size declarator or


initialization list when array is defined

8-16
• Processing Array Contents

 Array elements can be


 treated as ordinary variables of the same type as the array
 used in arithmetic operations, in relational expressions, etc.

 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

 Can not copy with an assignment statement:


tests2 = test; //won’t work

 Must instead use a loop to copy element-by-


element:
for (int k=0; k < ISIZE; k++)
tests2[k] = test[k];

8-19
Are Two Arrays Equal?

 Also, cannot compare in a single expression:


if (tests2 == test)
 Use a while loop with a boolean variable:
bool Equal = true;
int k = 0;
while (Equal && k < ISIZE)
{
if(test[k] != tests2[k])
Equal = false;
k++;
}
if(Equal == false){
Cout<<“arrays are not equal”;}
Else{ 8-20
Cout<<“arrays are equal”;}
Sum, Average of Array
Elements
 Usea simple loop to add together array
elements
float average, sum = 0;
for(int t=0; t< ISIZE; t++)
sum += test[t];
 Once summed, average can be computed
average = sum/ISIZE;
8-21
Largest Array Element
 Use a loop to examine each element and find the largest element
(i.e., one with the largest value)
int test[5] = {10,2,3,5,1};
int largest = test[0];
for (int t = 1; t < ISIZE; t++)
{
if (test[t] > largest)
largest = test[t];
}
cout << "Highest score is " << largest;
 A similar algorithm exists to find smallest.
8-22
Partially-Filled Arrays

 Theexact amount of data may not be


known when a program is written.
 Programmer estimates maximum amount
of data (capacity), and sizes array
accordingly.
 Programmer must keep track of how many
array elements are actually used – to
avoid exceeding array capacity
(segmentation error)
8-23
C-Strings and string Objects

Can be processed using array name


 Entirestring at once, or
 One element at a time by using a subscript

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

const int ISIZE = 5;


string name[ISIZE]; // student name
float average[ISIZE]; // course average
char grade[ISIZE]; // course grade

name average grade


0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
8-26
Parallel Array Processing
const int ISIZE = 5;
string name[ISIZE]; // student name
float average[ISIZE]; // course average
char grade[ISIZE]; // course grade
...
for (int i = 0; i < ISIZE; i++)
cout << " Student: " << name[i]
<< " Average: " << average[i]
<< " Grade: " << grade[i]
<< endl;
8-27
• The typedef Statement

 Creates an alias for a data type.


 Format:

typedef existingType newName;

 Example:

typedef float Money;


Money Paycheck[ISIZE]; // array of
// floats.

8-28
Uses of typedef

 Can make code more readable.


 Can be used to create alias for array of a particular
type

// Define yearArray as a data type


// that is an array of 12 ints
typedef int yearArray[MONTHS];

8-29

Das könnte Ihnen auch gefallen