5 All
5 All
OVERVIEW
OVERVIEW
In many programs, we need to store and process a lot of
data with the same data type
Processing test scores to find the class average
Tabulating bank deposits and withdrawals
Displaying images on a computer screen
Lesson objectives:
Learn the syntax for declaring arrays in C++
Learn how to store and process data in arrays
Learn how to search and sort data in arrays
Study example programs showing their use
Complete online labs on arrays
Complete programming project using arrays
PART 1
ARRAY BASICS
DECLARING ARRAYS
Arrays were invented to conveniently store multiple
values of the same data type in one variable
Picture an array as a long box divided into N slots
0 1 2 3 … N-1
float Data[100];
One float takes 4 bytes
Array size is 100 * 4 = 400 bytes
char name[20];
One char takes 1 byte
Array size is 20 * 1 = 20 bytes
PART 2
SEARCHING AND SORTING
SEARCHING ARRAYS
Once we have stored a collection of values in an array, we
can search the array to answer a number of questions:
Does a specific value (like 7) occur in array?
What is the maximum value in array?
What is the minimum value in array?
2 6 5 3 5 8 9 7
min max
specific
value
2 3 5 5 6 7 8 9
min max
2 3 5 5 6 7 8 9
Look at middle location (0+7)/2 = 3, which contains 5
2 3 5 5 6 7 8 9
2 3 5 5 6 7 8 9
2 3 5 5 6 7 8 9
2 3 5 5 6 7 8 9
2 3 5 5 6 7 8 9
Look at middle location (0+7)/2 = 3, which contains 5
2 3 5 5 6 7 8 9
2 3 5 5 6 7 8 9
2 3 5 5 6 7 8 9
2 3 5 5 6 7 8 9
2 3 5 5 6 7 8 9
2 3 5 5 6 7 8 9
2 3 5 5 6 7 8 9
Min = Mid+1;
… We change lower array index
here to be 1 to right of midpoint
CP 123: Introduction to High Level Programming
BINARY SEARCH
…
// Change max to search left half
else if (Data[Mid] > Desired)
Max = Mid-1;
3 1 4 1 5 9 2 6
min
sorted - unsorted
1 3 4 1 5 9 2 6
min
sorted - unsorted
1 1 4 3 5 9 2 6
min
sorted - unsorted
1 1 2 3 5 9 4 6
min
sorted - unsorted
1 1 2 3 5 9 4 6
min
sorted - unsorted
1 1 2 3 4 9 5 6
min
sorted - unsorted
1 1 2 3 4 5 9 6
min
sorted - unsorted
1 1 2 3 4 5 6 9
min
sorted - unsorted
1 1 2 3 4 5 6 9
sorted - unsorted