Title: Arrays
1Arrays Structures
Chapter 9
2Overview
- Declaring and Using a One-Dimensional Array
- Passing an Array as a Function Argument
- Using const in Function Prototypes
- Parallel Arrays
3C Data Types
structured
simple
array struct union class
integral enum
char short int long bool
4Structured Data Type
- A structured data type is a type that
- stores a collection of individual components
under a SINGLE variable name - Each component can be accessed sperately
- Arrays
- Indexed components (bracket notation)
- Uniform type
- Structures
- Named components (dot notation)
- Can have different types
5Declare variables to store and total 3 blood
pressures
- int bp1, bp2, bp3
- int total
-
4002
4000
4004
bp2
bp1
bp3
cin gtgt bp1 gtgt bp2 gtgt bp3
total bp1 bp2 bp3
6What if you wanted to store and total 1000 blood
pressures?
- int bp1000
- // declares an array of 1000 int values
7One-Dimensional Array Definition
- An array is a structured collection of components
- same data type
- given a single name
- stored in adjacent memory locations
- The individual components are accessed by using
the array name together with an integral valued
index in square brackets StudentID5 - The index indicates the position of the component
within the collection.
8Another Example
- Declare an array called temps which will hold up
to 5 individual float values. - float temps5 //allocates memory
number of elements in the array
Base Address
7000 7004 7008 7012
7016
temps0 temps1 temps2 temps3
temps4
indices or subscripts
9Declaration of an Array
- The index is also called the subscript
- In C, the first array element always has
subscript 0. The second array element has
subscript 1, etc. - The base address of an array is the smallest
memory address of the bytes within the array - The array is stored in contiguous bytes
- SYNTAX
- DataType ArrayName ConstIntExpression
10Yet Another Example
- Declare an array called name which will hold up
to 10 individual char values. - char name10//allocates memory
number of elements in the array
Base Address
6000 6001 6002 6003 6004 6005
6006 6007 6008 6009
name0 name1 name2 name3 name4
. . . . .
name9
11Assigning Values to Individual Array Elements
- float temps 5 // allocates memory
- int m 4
- temps 2 98.6
- temps 3 101.2
- temps 0 99.4
- temps m temps 3 / 2.0
- temps 1 temps 3 - 1.2
7000 7004 7008 7012
7016
99.4 ? 98.6 101.2
50.6
temps0 temps1 temps2 temps3
temps4
12What values are assigned?
- float temps 5 // allocates memory
- int m
- for (m 0 m lt 5 m) // will run 4 times
-
- temps m 100.0 m
7000 7004 7008 7012
7016
? ? ? ?
?
temps0 temps1 temps2 temps3
temps4
13Now what values are printed?
- float temps 5
- int m
- for (m 4 m gt 0 m--)
-
- cout ltlt temps m ltlt endl
-
7000 7004 7008 7012
7016
100.0 101.0 102.0 103.0
104.0
temps0 temps1 temps2 temps3
temps4
14Variable Subscripts
- float temps5
- int m 3
- //assume each value below is assigned
- What is temps m 1 ?
- What is temps m 1 ?
7000 7004 7008 7012
7016
100.0 101.0 102.0 103.0
104.0
temps0 temps1 temps2 temps3
temps4
15A Closer Look at the Compiler
- float temps5
- To the compiler, the value of the identifier
temps alone is the base address of the array. We
say temps is a pointer (because its value is an
address). It points to a memory location.
16Initializing in a Declaration
- int ages 5 40, 13, 20, 19, 36
- for (int m 0 m lt 5 m)
- cout ltlt ages m
17Passing Arrays as Arguments
- in C, arrays are always passed by reference
- whenever an array is passed as an argument, its
base address is sent to the called function
18Using Arrays as Arguments to Functions
- Generally, functions that work with arrays
require 2 items of information as arguments - the beginning memory address of the array (base
address) - the number of valid elements in the array ( you
will want to send this as a separate parameter)
19Size vs. Capacity
- The capacity of an array is the number of
elements that can be stored in the memory area
set aside by the compiler - Capacity is specified at declaration, and does
not change - The effective size of an array is the number of
valid elements actually stored in the array - Size changes as the program runs
20Use of const
- because the identifier of an array holds the base
address of the array, an is never needed for an
array in the parameter list - arrays are always passed by reference
- to prevent elements of an array used as an
argument from being changed by the function, you
place const in the function heading and prototype -
- void Print(const int temp , int number)
21Use of const in prototypes
do not use const with outgoing array
because function is supposed to change array
values
- void Obtain (int , int)
-
- void FindWarmest (const int , int, int)
- void FindAverage (const int , int, int)
- void Print (const int , int)
use const only with incoming array values to
prevent unintentional changes by function
22Example with Array Parameters
include ltiomanipgt include ltiostreamgt void
Obtain ( int , int ) // prototypes here
void FindWarmest ( const int , int , int
) void FindAverage ( const int , int ,
int ) void Print ( const int , int )
using namespace std int main () int
temp31 // array to hold up to 31 ints
int numDays int average int
hottest int m
23Example continued
cout ltlt "How many daily temperatures? "
cin gtgt numDays Obtain( temp, numDays )
// call passes value of numDays and //
address of array temp to function cout ltlt
numDays ltlt " temperatures" ltlt endl Print
(temp, numDays) FindAverage (temp, numDays,
average) FindWarmest (temp, numDays,
hottest) cout ltlt endl ltlt "Average was
" ltlt average ltlt endl cout ltlt
"Highest was " ltlt hottest ltlt endl return
0
24Memory Allocated for Array
int temp31 // array to hold up to 31
temperatures
25void Obtain (int temp, //output temps
int number //input of temp ) //prompts
for ltnumbergt temperatures //Precondition number
gt 0 //Postcondition temp0tempnumber -1
int m for ( m 0 m lt number m
) cout ltlt Enter a temperature
cin gtgt temp m
26void Print (const int temp, int
number ) // Prints number temperature
values // Precondition number gt 0 // temp 0 . .
number -1 are assigned int m
cout ltlt "You entered " for ( m 0 m lt
number m ) if ( m 5 0 )
cout ltlt endl cout ltlt setw(7)
ltlt temp m
27void FindAverage (const int temp,
int number, int
avg ) // Determines average of temp0 . .
number-1 // Precondition // number is
assigned number gt 0 // temp 0 . . number
-1 are assigned // Postcondition // avg
arithmetic average of temp int m
int total 0 for ( m 0 m lt number
m ) total total temp m
avg int(float(total)/float(number)
.5) // avg total/number
28void FindWarmest (const int temp , //in
int number,
//in int largest
//out) /Determines largest of temp0 . .
number-1 Precondition number is assigned
number gt 0 temp 0 . . number -1 are
assigned Postcondition largestlargest value in
temp0...number-1 / int m largest
temp0 //set largest to 1st element // then
compare with other elements for ( m 0 m
lt number m ) if ( temp m gt
largest ) largest tempm
29More about Array Index
- Array index can be any integral type
- This includes char and enum types
- It is the programmers responsibility to make
sure that an array index does not go out of
bounds - The index must be within the range 0 through the
declared array capacity minus one - Using an index value outside this range causes
the program to access memory locations outside
the array - The index value determines which memory location
is used
30Searching
- Consider the problem of finding the smallest
element in an array of doubles
findPosOfSmallest(double array, int N) - One approach is
- Set posOfSmallest 0, j 1
- If arrayj lt arrayposOfSmallest then set
posOfSmallest j - Increment j
- Repeat steps 2 3 until we reach the end of the
array
31Searching for Smallest
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
The arrows indicate the element that is being
checked. The grayed boxes indicate the best guess
at the smallest element.
32Searching for Smallest
- int findPosOfSmallest(double array, int N)
-
- int bestGuess
- startIndex 0 // start looking for smallest
at index 0 - bestGuess startIndex // smallest element
encountered - for (int j startIndex 1 j lt N j)
-
- if (arrayj lt arraybestGuess)
-
- bestGuess j
-
-
- return bestGuess
33Sorting
- Suppose we are given an array of numbers of size
N that we wish to order from smallest to largest - There are many algorithms for sorting numbers
- One of the, selection sort, uses a modified
version of the find smallest function from the
previous slides - The selection sort provides one method of
sorting - Create a second array that has the same size as
the original array - Find the smallest number in the original array
- Put that number in the next empty entry in the
second array - Remove that number from the original array
(assign that cell a really big value) - Repeat steps 2 to 4 until they have been
performed N times
34Selection Sort
new array (sorted)
original array
Initialization
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
35Selection Sort
- Though we cannot actually remove an element from
an array, we could replace the smallest value in
the array with a very large number - When we search for the next smallest number, that
large value will be skipped - for (i 0 i lt N i)
-
- posOfSmallest findPosOfSmallest(originalArray,N
) - sortedArrayi originalArrayposOfSmallest
- originalArrayposOfSmallest MAX_DOUBLE
-
36Selection Sort
- The code shown in the previous slide is not good
- it requires two arrays
- this is a waste of memory resources
- A more efficient method would be
- Set counter i 0
- Find the smallest number in the original array
with index gt i - Swap that element with the element at index i
- Increment i
- Repeat steps 2 to 4 until they have been
performed N-1 times
37Selection Sort
Initialization
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
The arrows indicate elements being swapped. The
grayed boxes indicate elements that are already
sorted.
38Selection Sort
This function must be modified so that it
searches the array (size N) for the smallest
element, but only considers elements with index i
or greater.
- include ltiostream.hgt
- int main()
- const int N 6 // size of array to be sorted.
- double arrayN 9,3,8,2,6,5 // array to be
sorted - int posOfSmallest
- double temp
- for (int i 0 i lt (N-1) i)
- posOfSmallest findPosOfSmallest(array, i, N)
- temp arrayi
- arrayi arrayposOfSmallest
- arrayposOfSmallest temp
-
- return 0
39Searching for Smallest
- int findPosOfSmallest(double array, int i, int
N) -
- int bestGuess
- startIndex i // start looking for smallest
at index i - bestGuess startIndex // smallest element
encountered - for (int j startIndex 1 j lt N j)
-
- if (arrayj lt arraybestGuess)
-
- bestGuess j
-
-
- return bestGuess