Professional Documents
Culture Documents
Chapter 11
Arrays
Objectives
One-Dimensional Arrays
Array Initialization
Declaring and Processing Two-Dimensional
Arrays
Applications
Arrays as Arguments
Objectives (continued)
The STL Vector Class
Common Programming Errors
Searching and Sorting
One-Dimensional Arrays
One-dimensional array: a list of related values
with the same data type, stored using a single
group name (called the array name)
Syntax:
dataType arrayName[number-of-items]
10
11
Array Initialization
Array elements can be initialized in the array
declaration statement
Example:
12
13
14
15
16
17
18
19
Applications
Statistical Analysis: Create a program that:
Accepts a list of 100 voltages as input
Calculates the average and standard deviation
Displays the results of the calculations
20
Arrays as Arguments
21
22
23
24
25
26
27
28
Summary
Single dimension array is a data structure that
stores a list of values having the same data
type
Array elements are stored in contiguous
memory locations, and referenced by array
name and index position
Two-dimensional array has rows and columns
Arrays may be initialized when they are
declared
29
Summary (continued)
Arrays may be passed to a function by passing
the name of the array as the argument
Individual array elements as arguments are
passed by value
Arrays passed as arguments are passed by
reference, not by value
30
31
Search Algorithms
Searches can be faster if the data is in sorted
order
Two common methods for searching:
Linear search
Binary search
32
Linear Search
33
34
Binary Search
Binary Search requires that the list is stored in
sorted order
Desired item is compared to the middle
element, with 3 possible outcomes:
Desired element was found - finished
Desired element is greater than the middle
element, so discard all elements below
Desired element is less than the middle element,
so discard all elements above
C++ for Engineers and Scientists, Second Edition
35
36
37
38
39
Big O Notation
Big O Notation
represents the order of magnitude of
40
Sort Algorithms
Selection sort
Smallest element is found and exchanged with
the first element
Next smallest element is found and exchanged
with the second element
Process continues n-1 times, with each pass
requiring one less comparison
41
42
43
44