Arrays - bhecker.com

Download Report

Transcript Arrays - bhecker.com

Arrays
Chapter 12
Overview
•
•
•
•
•
Arrays and their properties
Creating arrays
Accessing array elements
Modifying array elements
Loops and arrays
Arrays and Their Properties
•
•
•
•
•
Hold several values of the same type
Based on a slot number (the index number)
Instant access
Linear (one after the other)
Static – once their size is set, it’s set…
Arrays Hold Multiple Values
Regular variable
count
int count;
5
Variable count stores one value of type int
Array variable
int days[ 3 ];
days
Allocates memory for 3 ints
2
3
1st element
2nd element
4
3rd element
Array days stores 3 values of type int
4
What arrays look like
• Things to notice
0
1
2
3
4
5
6
myArray
• There are 7 slots, with index numbers 0 – 6
• The name of the array is myArray
• Easy to be off by one
Creating Arrays
<data type> <name> [<size>];
• Notice that we can create an array of any data
type, just by changing the data type!
Examples
•
An array of shorts:
short someArray [50];
•
An array of floats:
float myArray [25];
•
An array of booleans:
bool list [65];
•
An array of chars:
char characters [255];
Modifying an Array
• You must specify which slot you are putting information in
• Example:
int myArray [50];
myArray [ 3 ] = 12;
0
1
• This won’t work:
int myArray [50];
myArray = 12;
• Data type on the left of = is an array
• Data type on right of = is an int
2
3
4
12
…
49
Accessing Information
• Copying information out of a particular slot
int clientAge;
clientAge = myArray [ 4 ];
• This copies information from the fifth slot (slot
four) into the variable clientAge
Initializing Arrays
(large arrays)
• For most arrays, you will use a loop to initialize
• Example: Create an array of 5 bytes and fill each
slot with the number 42
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
0
1
2
3
4
0
0
0
0
0
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
0
0
0
0
0
0
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
0
0
0
0
0
0
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
0
0
0
0
0
0
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
0
0
0
0
0
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
0
0
0
0
1
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
0
0
0
0
1
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
0
0
0
0
1
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
0
0
0
1
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
0
0
0
2
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
0
0
0
2
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
0
0
0
2
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
42
0
0
2
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
42
0
0
3
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
42
0
0
3
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
42
0
0
3
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
42
42
0
3
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
42
42
0
4
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
42
42
0
4
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
42
42
0
4
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
42
42
42
4
Line by Line
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
42
42
42
5
Line by Line
false
byte myList [5];
for (int counter = 0; counter < 5; counter++) {
myList [counter] = 42;
}
counter
0
1
2
3
4
42
42
42
42
42
5
Finding the Smallest Element
• If you were given an array of numbers, how
would YOU do it?
• Computers can only compare two at a time
• Go through entire list
• Keep track of smallest so far
• Let’s assume
– We have an array of 5 ints
– The array contains random unknown numbers
– The name of the array is called randomArray
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
} // if
} // for
0
1
2
3
4
42
17
42
-8
4
smallestSoFar
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
} // if
} // for
0
1
2
3
4
42
17
42
-8
4
smallestSoFar
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
} // if
} // for
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
42
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
1
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
42
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
1
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
42
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
Is 42 > 17?
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
1
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
42
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
1
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
17
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
1
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
17
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
2
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
17
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
2
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
17
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
Is 17 > 42?
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
2
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
17
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
2
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
17
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
3
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
17
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
3
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
17
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
Is 17 > -8?
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
3
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
17
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
3
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
-8
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
3
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
-8
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
4
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
-8
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
4
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
-8
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
Is -8 > 4?
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
4
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
-8
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
4
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
-8
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
5
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
-8
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
5
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
-8
Another Trace
int smallestSoFar;
smallestSoFar = randomArray[0];
for (int counter = 1; counter < 5; counter++) {
if (smallestSoFar > randomArray[counter]) {
smallestSoFar = randomArray[counter];
counter
} // if
} // for
5
0
1
2
3
4
smallestSoFar
42
17
42
-8
4
-8
Passing Arrays to Functions
#include <iostream.h>
void modifyArray (int inArray[ ], int arraySize) {
// Stuff that changes the array
}
void main ( ) {
int myArray [15];
modifyArray (myArray, 15);
}
The Overall Concept
•
•
•
•
•
Arrays hold values that are all the same type
Arrays are static in size
Creating arrays always follows a format
You can create an array of any type
To initialize or search arrays, you’ll almost
always use a loop
More on Initializing Arrays
Initialize all three indexed variables of the array “a”
int a[ 3 ] = { 2, 12, 1 };
is equivalent to:
int a[ 3 ];
a[ 0 ] = 2;
a[ 1 ] = 12;
a[ 2 ] = 1;
Automatically sized
int b[ ] = { 5, 12, 11 }; is equivalent to: int b[ 3 ] = { 5, 12, 11 };
If fewer values are listed than there are indexed variables, remaining
indexed variables are initialized to zero of the array base type
int c[ 5 ] = { 2, 4, 8 }; Only initializes first 3 elements of 5 element array
2
4
8
0
0
Un-initialized elements set to zero
62
Initializing Strings
If string constant is used, null terminator is automatically included
Element
data type
Sized automatically to length of
char short_str [ ] = “abc”; string + 1 for the ‘\0’
Is equivalent to:
char short_str [ 4 ] = “abc”;
‘a’
‘b’
Is not equivalent to:
char short_str [ ] = {‘a’, ‘b’, ‘c’};
‘c’ ‘\0’
‘a’
‘b’
‘c’
Character array also has indexed variables
short_str[ 0 ]
short_str[ 1 ]
short_str[ 2 ] . . .
Loop ends when element is \0
int index = 0;
while ( short_str [ index ] != ‘\0’ )
{
short_str [ index ] = ‘X’; Change value in short_str to
contain all ‘X’ characters
index++;
}
63
More Array Processing
Processing array elements is the same as processing other variables
int score[ 5 ] = { 7, 8, 9, 10, 0 };
Increment value in score[ 2 ]
int result = score [ 4 ] * 2; Initializes result to value of
score[ 4 ] times 2
++ score [ 2 ];
if ( score[ 3 ] < score[ 4 ] )
while ( score[ count ] != 0 )
Is the value in score[ 3 ] less
than the value in score[ 4 ]?
Loop iterates as long as
score[ count ] does not equal 0
64
Parallel Arrays
Using two or more arrays to represent relationships
involving different data types
const int NUMEMPS;
Number of employees
Elements int hours [NUMEMPS]; Stores hours worked by each
employee
are integers
Elements float payRate [NUMEMPS]; Stores pay rate for each
employee
are floats . . .
for ( int index = 0; index < NUMEMPS; index++ )
{
cout << “Hours employee #” << ( index + 1 );
cin >> hours[ index ];
cout << “Pay rate employee #” << ( index + 1 );
cin >> payRate[ index ];
}
Same index used to
access both arrays
65
Printing Array Contents
Use a loop to display the contents of each array
element
Declare and
int testArr [ 5 ] = { 10, 20, 30, 40, 50 }; initialize array
Doesn’t work!
cout << testArr << endl;
Displays address of the
array, not the contents
Works!
Loop displays value
for ( int ct = 0; ct < 5; ct++ )
cout << testArr [ ct ] << endl; of each element
Exception: Displaying the contents of a
char array containing a C-string
char name [ ] = “Ned Nerd”; Displays string, not array address
cout << name << endl;
cout uses \0 when given a char array to determine end of the string
66
Array Elements as Function Arguments
With each loop iteration, the value contained in testArr[ct] is
passed to the function showVal
void showVal ( int num );
Program output:
void main ( )
5 10 15 20 25
{
int testArr [ 5 ] = { 5, 10, 15, 20, 25 };
for ( int ct = 0; ct < 5; ct++ )
showVal ( testArr [ ct ] ); Array element, type int, as the
argument
}
void showVal ( int num )
{
cout << num << “ “;
}
Parameter is also type int
Array elements can be passed by value or by reference
67
Arrays as Function Arguments
Any changes to parameter nums, effect argument testArr
void showVal ( int nums [ ] );
void main ( )
Program output:
{
5 10 15 20 25
int testArr [ 5 ] = { 5, 10, 15, 20, 25 };
showVal ( testArr ); Starting address of array is passed to
}
function showVal
void showVal ( int nums [ ] )
{
for ( int ct = 0; ct < 5; ct++ )
cout << nums [ ct ] << “ “;
}
0
1
2
testArr
5
10
15
3
4
20
25
nums[0] nums[1] nums[2] nums[3] nums[4]
68
Arrays as Function Arguments
Use two arguments: The address of the array
The size of the array
Modify function showVal to display the contents of an int array of
any size
In
main:
int testArr1 [ 2 ] = { 5, 10 };
int testArr2 [ 5 ] = { 5, 10, 15, 20, 25 };
int testArr3 [ 7 ] = { 5, 10, 15, 20, 25, 30, 35 };
showVal ( testArr1, 2 );
Function calls
showVal ( testArr2, 5 );
to showVal
showVal ( testArr3, 7 );
New
showVal:
Address of array
Size of array
void showVal ( int nums [ ], int size )
{
for ( int ct = 0; ct < size; ct++ )
cout << nums [ ct ] << “ “;
}
69
Arrays as Function Arguments
Array parameters give direct access to the array argument
void doubleArr ( int nums [ ], int size );
void main ( )
{
Program output:
int testArr [ 5 ] = { 1, 2, 3, 4, 5 };
for ( int ct = 0; ct < 5; ct++ )
1 2 3 4 5
cout << testArr [ ct ] << “ “;
2 4 6 8 10
doubleArr ( testArr, 5 );
for ( int ct = 0; ct < 5; ct++ )
cout << testArr [ ct ] << “ “;
}
void doubleArr ( int nums [ ], int size )
{
for ( int i = 0; i < size; i++ ) Changes values in
parameter nums and
nums [ i ] *= 2;
argument testArr
}
70
Two-dimensional Arrays
Two-dimensional array is several identical arrays put
together in the form of a table
Exam scores
column 0
column 1
column 2
row 0
score[0][0]
score[0][1]
score[0][2]
Students row 1
score[1][0]
score[1][1]
score[1][2]
row 2
score[2][0]
score[2][1]
score[2][2]
Number of rows
float score [ 3 ] [ 3 ];
Number of columns
Assign value to an element
score [ 1 ] [ 2 ] = 93.2;
Row index
cout << score [ 0 ] [ 2 ];
Column index
Display value of an element
71
Two-dimensional Arrays
Nested loops are used to process each element of a
two-dimensional array
float score [ 3 ] [ 3 ];
for ( int std = 0; std < 3; std++ ) Outer loop iterates over rows
{
Inner loop iterates over columns
for ( int exam = 0; exam < 3; exam++ )
{
cout << “Student “ << std + 1 << “ , exam “ << exam + 1 << “: “;
cin >> score [ std ] [ exam ]; Read in an exam score
}
Row
Column
Program output:
cout << endl;
index
index
}
Student 1, exam 1: 92.3
score 0
1
2
Student 1, exam 2: 88.5
0
Student 1, exam 3: 83.6
92.3
88.5
83.6
Student 2, exam 1: 79.2
1
79.2
72.8
?
Student 2, exam 2: 72.8
2
. . .
?
?
?
72
Two-dimensional Arrays as
Function Arguments
Number of columns is specified in a two-dimensional
array parameter Empty Column index
Number of rows
void showArr ( int Arr [ ] [ 2 ], int rows );
void main ( )
Extra braces that enclose each
{
row’s values are optional
int table [ 3 ] [ 2 ] = { { 8, 5 }, { 7, 9 }, { 6, 3 } };
showArr ( table, 3 );
Row 1 Row 2
Row 3
}
void showArr ( int Arr [ ] [ 2 ], int rows )
{
for ( int r = 0; r < rows; r++ ) Iterates rows
Program output:
{
for ( int c = 0; c < 2; c++ ) Iterates columns
8 5
cout << Arr [ r ] [ c ] << “ “;
7 9
cout << endl;
6 3
}
}
73
Arrays Strings
A two-dimensional array of characters can be used
as multiple arrays of strings
char team [ 4 ] [ 9 ] = { “Ned”, “Connie”, “Pat”, “Greg” };
0
N
e
d
\0
1
C
o
n
n
2
P
a
t
\0
3
G
r
e
g
Four names,
8 characters long
i
e
\0
\0
Maximum length of
string is 9 – 1
(for null terminator)
Name of array with only a row index is the address of
that row
Pat
cout << team [ 2 ];
Loop displays all names in the array
for ( int ct = 0; ct < 4; ct++ )
cout << team [ ct ] << endl;
Ned
Connie
Pat
Greg
Program
output:
74
End of Lecture 4
• Next Time, more on Arrays