Chapter 7 Arrays - PowerPoint PPT Presentation

1 / 20
About This Presentation
Title:

Chapter 7 Arrays

Description:

To demonstrate how for-loops are used to traverse arrays ... passed by reference, but without the ampersand marking it as passed-by-reference. ... – PowerPoint PPT presentation

Number of Views:47
Avg rating:3.0/5.0
Slides: 21
Provided by: william732
Learn more at: http://www.cs.siue.edu
Category:

less

Transcript and Presenter's Notes

Title: Chapter 7 Arrays


1
Chapter 7Arrays
Goals
  • To introduce the concept of array variables
  • To demonstrate how for-loops are used to
    traverse arrays
  • To explain how arrays are stored in RAM
  • To illustrate how arrays can be initialized in
    C
  • To demonstrate how arrays can be used as
    parameters
  • To examine common array operations (sorting
    searching)

2
Array Variables
When dealing with several values of the same
type, which are used for similar purposes within
a program, it is often convenient to use a single
variable to hold the values.
int hourlyReading24
This variable declaration reserves space in RAM
for 24 integer values, which are referred to
within the program as hourlyReading0 through
hourlyReading23.
3
include ltiostreamgt include ltiomanipgt using
namespace std void main() int
hourlyReading24 int i for (i 0 i lt
24 i) cout ltlt setw(2) ltlt (i 12
1) ltlt " o\'clock reading " ltlt hourlyReadingi
if (i 3 2) cout ltlt endl
else cout ltlt '\t' for (i 0
i lt 24 i) hourlyReadingi -1
hourlyReading3 300 hourlyReading7
700 hourlyReading9 900
hourlyReading12 1200 hourlyReading20
2000 hourlyReading23 2300 cout ltlt
endl ltlt endl for (i 0 i lt 24 i)
cout ltlt setw(2) ltlt (i 12 1) ltlt " o\'clock
reading " ltlt setw(4) ltlt hourlyReadingi
if (i 3 2) cout ltlt endl
else cout ltlt '\t' cout ltlt
endl
Notice that the first value in the array is
indexed at 0, not 1!
One value in the array may be output, but not the
whole array at once!
Assignment statements may be used with one value
in the array, but not with the whole array!
4
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
Contents of values.txt
Resulting Output
5
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
98.64537 99.00128 96.78349
97.00226 98.55201 98.66297 98.06629
98.63230 98.60001 98.71102 98.81553
98.25172 98.67235 98.82376 96.82326
97.80251 98.99209 98.34278 99.00189
97.12194
?
98.64537
0
?
99.00128
1
?
96.78349
96.78349
98.81553
2
?
97.00226
97.00226
98.25172
98.25172
98.82376
If the array isnt already full (i.e., if
nbrOfVals does not equal 10), then just insert at
the end of the list!
3
?
98.55201
98.55201
98.99209
4
?
98.66297
5
?
98.06629
98.06629
98.67235
6
If the array is already full, then find the
smallest entry in the array and, if its smaller
than the new value, do a replacement!
?
98.63230
98.63230
98.63230
7
?
98.60001
98.60001
99.00189
8
?
98.71102
9
6
Whats Happening in Memory?
When an array variable is declared, the size of
the array and the number of bytes required for
one variable of the designated type are
multiplied. The product is the number of
consecutive bytes allocated for the array
variable.
4 bytes per int 20 bytes total
int weekdayTotal5 char password12
1 byte per char 12 bytes total
RAM
weekdayTotals memory
passwords memory
7
include ltiostreamgt include ltiomanipgt include
ltcmathgt using namespace std void main() int
twoPower30 int i for (i 0 i lt 30
i 1) twoPoweri int(pow(2,i))
cout ltlt setw(2) ltlt i ltlt " " cout ltlt
twoPoweri ltlt endl return
Improper Indexing
The compiler will not detect a problem when an
array is indexed improperly, but an error may
occur during executio
8
More Improper Indexing
Its possible that no error will be detected,
even during execution. But that still doesnt
mean that the program will work!
Notice how the nbr variable got assigned a new
value by mistake? Apparently, nbr is being held
in the RAM position right after the last entry in
the twoPower array. Since the system sees that
that memory is being used by the program, it
doesnt object to loading it with a value!
include ltiostreamgt include ltiomanipgt include
ltcmathgt using namespace std void main() int
nbr 0 int twoPower6 int i for (i
0 i lt 6 i 1) twoPoweri
int(pow(2,i)) cout ltlt setw(2) ltlt i ltlt "
" cout ltlt twoPoweri ltlt endl cout
ltlt "nbr equals " ltlt nbr ltlt endl ltlt
endl return
9
While assignment operators cannot normally be
used to assign values to entire arrays, they can
be used to initialize arrays when theyre being
declared.
Array Initialization
1
2
1) If the array size is specified and the number
of initialized values is too low, all remaining
slots are filled with zeroes.
2) If the array size is unspecified, then its
set to the number of initialized values.
10
Passing Array Entries to Functions
Array entries may be passed to functions by value
or by reference, just like regular variables.
Since the parameter was passed by reference, the
alterations are actually being made to the value
in the array!
11
Original contents of GrossFile.txt
804.89 692.45 614.39 760.26 541.53 229.55
954.82 206.73 730.13 685.33 405.49 351.50
152.51 606.81 198.79 127.55 869.49 382.64
605.27 263.36 124.58 544.82 291.35 822.71
987.64 550.15 537.19 363.20 141.80
432.30 843.20 229.25 766.33 964.90 803.19
845.54 819.56 226.56 171.96 726.15 173.52
207.94 306.04 365.12 305.00 652.27 705.38
124.09 394.89 969.18 133.97 582.64 439.77
912.91 547.71 767.07 828.21 165.28 807.91
922.96 885.58 114.42 907.91 747.27 239.85
769.38 991.46 645.89 112.00 601.68 590.91
531.67 283.88 354.00 363.00 129.22 546.80
607.22 950.95 701.57 583.82 445.84 350.40
464.60 788.99 512.66 607.69 928.43 465.61
984.07 222.49 624.66
Final contents of GrossFile.txt
400.00 400.00 400.00 400.00 400.00 229.55
400.00 206.73 400.00 400.00 400.00 351.50
152.51 400.00 198.79 127.55 400.00 382.64
400.00 263.36 124.58 400.00 291.35 400.00
400.00 400.00 400.00 363.20 141.80
400.00 400.00 229.25 400.00 400.00 400.00
400.00 400.00 226.56 171.96 400.00 173.52
207.94 306.04 365.12 305.00 400.00 400.00
124.09 394.89 400.00 133.97 400.00 400.00
400.00 400.00 400.00 400.00 165.28 400.00
400.00 400.00 114.42 400.00 400.00 239.85
400.00 400.00 400.00 112.00 400.00 400.00
400.00 283.88 354.00 363.00 129.22 400.00
400.00 400.00 400.00 400.00 400.00 350.40
400.00 400.00 400.00 400.00 400.00 400.00
400.00 222.49 400.00
12
include ltiostreamgt using namespace std const
int LIST_SIZE 10 bool isPowerOfTwo(int
value) void main() int favoriteNbrLIST_SIZ
E 13,16,21,29,32,35,50,75,95,100 int i
int powerOfTwoCount 0 for (i 0 i lt
LIST_SIZE i) if (isPowerOfTwo(favori
teNbri)) powerOfTwoCount
cout ltlt "The List" ltlt endl for (i 0 i lt
LIST_SIZE i) cout ltlt favoriteNbri ltlt
endl cout ltlt endl ltlt powerOfTwoCount
ltlt " are powers of two!" ltlt endl ltlt endl
return bool isPowerOfTwo(int value)
while ((value 2 0) (value gt 1))
value / 2 return (value 1)
Setting up a constant for the array size
simplifies code modification if a different size
is needed later.
Another Example
Since the parameter was passed by value, the
alterations are made to the value of the copy,
not to the value in the array!
13
Passing An Entire Array To A Function
An entire array may be passed to a function as a
parameter, but only the memory location of the
array is actually passed. Thus, an array cannot
be passed by value it is essentially passed by
reference, but without the ampersand marking it
as passed-by-reference.
Each function prototype with an array parameter
must specify the type and use brackets to specify
that its an array, but since the parameter is
essentially passed by reference, its size need
not be specified here.
//////////////////////////////////////////////////
//// // This program retrieves a list of test
scores // // from a user-specified input
file. These scores // // are sorted and
averaged. Output includes the // // presorted
and sorted lists, as well as the mean.
// ///////////////////////////////////////////////
/////// include ltiostreamgt include
ltiomanipgt include ltfstreamgt include
ltcassertgt using namespace std const int
MAX_LIST_SIZE 50 void inputList(int list,
int listSize) void outputList(const int list,
int listSize) void sortList(int list, int
listSize) double averageList(const int list,
int listSize)
Since array parameters cannot be passed by value,
there is a danger that they might be
inadvertently altered within a function. To avoid
this, they can be modified with the const
designation, which prohibits the function from
changing their values.
14
// The main function supervises the input,
output, // // sorting, and averaging of a list
of test scores, // // including the output of the
list's mean value. // void main() int
testScoreMAX_LIST_SIZE int nbrStudents
inputList(testScore, nbrStudents) cout ltlt
endl ltlt "Presorted Scores" ltlt endl
outputList(testScore, nbrStudents)
sortList(testScore, nbrStudents) cout ltlt endl
ltlt "Sorted Scores" ltlt endl
outputList(testScore, nbrStudents)
cout.setf(iosfixed) cout.setf(iosshowpoint
) cout.precision(3) cout ltlt endl ltlt "The
mean score is " ltlt averageList(testScore,
nbrStudents) ltlt endl ltlt endl
return
When actually calling the function, the type of
the array parameter is not specified in the
function call. Similarly, the square brackets
designating the argument as an array and the size
of the array are not specified in the function
call.
15
// This function fills an array with the contents
of a user- // // specified input file, stopping
at the end of the file or // // the capacity of
the array, whichever comes first. // void
inputList(int list, int listSize)
ifstream inputFile char inputFileNameMAX_LIST
_SIZE int value cout ltlt "Enter the name
of the input file " cin gtgt inputFileName
inputFile.open(inputFileName)
assert(!inputFile.fail()) listSize 0
inputFile gtgt value while ((!inputFile.eof())
(listSize lt MAX_LIST_SIZE))
listlistSize value listSize
inputFile gtgt value inputFile.close()
return
Notice that a character string is just another
type of array. (Well see more details in the
next chapter.)
As long as there are more values in the input
file AND more room in the array being filled,
this loop keeps getting new entries for the array.
16
Notice that the array elements may be used, but
not altered in this function. This is because of
the const modifier of the list parameter.
Since the sorted array is needed in the main
function, no const modifier is employed in this
function.
Essentially, this nested loop keeps sliding
array entries over until it finds the slot where
currentValue belongs.
17
// This function computes the arithmetic mean of
the values in // // the parameterized array,
returning this mean value to the // // calling
function. Zero is returned if the array is
empty. // double averageList(const int list,
int listSize) int sum 0 int i if
(listSize 0) return 0 else
for (i 0 i lt listSize i) sum
listi return double(sum)/listSize
Again, this function shouldnt be altering the
arrays contents, so a const modifier is used.
18
An Alternative Sorting Algorithm
Many sorting algorithms have been developed. In
addition to the insertion sort weve already
seen, there is a selection sort
// This function performs an "selection sort" on
the parameterized // // array, sorting its
entries by finding the smallest entry and
// // swapping it with the first entry, then
finding the next smallest // // entry and
swapping it with the second entry, and so forth.
// void sortList(int list, int
listSize) int index int currentIndex
int smallestIndex int temp for
(currentIndex 0 currentIndex lt listSize - 1
currentIndex) smallestIndex
currentIndex for (index currentIndex
1 index lt listSize index) if
(listindex lt listsmallestIndex)
smallestIndex index if (smallestIndex !
currentIndex) temp
listcurrentIndex listcurrentIndex
listsmallestIndex listsmallestIndex
temp return
Notice that the functions name and parameter
list are identical with what was used in the
previous example. The principles of information
hiding are thus upheld, and this new sorting
algorithm can replace the old one with no other
changes to the program!
Essentially, this nested loop keeps finding the
kth smallest entry and swapping it with whats in
array slot (k-1).
19
Searching An Unsorted Array
The most common algorithm for searching for a
particular value within an unsorted array is the
sequential search
// This function performs a sequential search of
the parameterized // // array for the
parameterized value. Starting at the top of the
// // array, it examines each entry, returning a
boolean value of true // // as soon as it finds
the value, or a boolean value of false if it
// // traverses the entire array without locating
the value. // bool searchList(const int
list, int listSize, int soughtValue) int
i for (i 0 i lt listSize i) if
(listi soughtValue) return true
return false
Because the number of comparisons executed in
this algorithm is, on average, directly
proportional to the number of elements in the
array, this algorithm is also known as a linear
search.
20
// This function performs a binary search of the
parameterized // // array for the parameterized
value. Starting at the middle // // of the
array, it compares that entry to the sought
value, // // returning a boolean value of true
if they're equal, but // // eliminating the
first half of the list from any further
// // consideration if the middle value is too
small or the second // // half if the middle
value is too large. It continues halving // //
the list until it actually finds the sought
value, in which // // case it returns a boolean
value of true, or until it // //
eliminates the entire array from consideration,
in which it // // returns a boolean value of
false. // bool
searchList(const int list, int listSize, int
soughtValue) int lowIndex 0 int
highIndex listSize -1 int middleIndex
while (lowIndex lt highIndex)
middleIndex (lowIndex highIndex) / 2
if (listmiddleIndex soughtValue)
return true else if (listmiddleIndex lt
soughtValue) lowIndex middleIndex
1 else highIndex middleIndex -
1 return false
Searching A Sorted Array
The most common algorithm for searching for a
particular value within a sorted array is the
binary search.
Notice that the number of comparisons executed in
this algorithm is, on average, directly
proportional to the base-2 logarithm of the
number of elements in the array.
Write a Comment
User Comments (0)
About PowerShow.com