0% found this document useful (0 votes)
15 views

5 All

The document discusses arrays in C++. It covers declaring, initializing, and accessing arrays. It also discusses using loops to process arrays by reading/writing values or calculating totals. The section describes searching and sorting arrays.

Uploaded by

LAURENT JIBUNGE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

5 All

The document discusses arrays in C++. It covers declaring, initializing, and accessing arrays. It also discusses using loops to process arrays by reading/writing values or calculating totals. The section describes searching and sorting arrays.

Uploaded by

LAURENT JIBUNGE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

ARRAYS

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

 Arrays in C++ give us a way to accomplish this goal


 Declare an array of desired data type and size
 Store data values in each array location
 Process data values to solve a specific problem

CP 123: Introduction to High Level Programming


OVERVIEW
 How do we process data in arrays?
 Depends on needs of the application
 Some applications create summaries of data in array
 Some applications print a subset of data in array
 Some applications search for data in the array
 Some applications move data around in the array

 How to we implement this array processing?


 Use iteration to loop over array elements
 Use functions to simplify code reuse

CP 123: Introduction to High Level Programming


OVERVIEW
 We need to learn a variety of array processing algorithms
in order to become strong C++ programmers

 Each array processing algorithm has its pros/cons


 Some have faster run times, some are slower
 Some take more memory, some take less memory
 Some are complex to implement, some are simple

 To understand these differences, we must learn scientific


methods for algorithm analysis and program testing

CP 123: Introduction to High Level Programming


OVERVIEW

 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

CP 123: Introduction to High Level Programming


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

 Array elements are stored in separate memory locations


and accessed based on their position
 The first array element is in location 0
 The last array element is in location N-1

CP 123: Introduction to High Level Programming


DECLARING ARRAYS
 The syntax for an array declaration is:
data_type array_name [ array_size ];
where
data_type can be any basic C++ type (int, float, etc.)
array_name follows C++ variable name rules
array_size is an integer or integer constant

CP 123: Introduction to High Level Programming


DECLARING ARRAYS

// Valid array declarations


float Data[100];
The array_size can be
int List[20];
given with an integer
const int SIZE = 50; literal or constant
char Name[SIZE];

CP 123: Introduction to High Level Programming


DECLARING ARRAYS

// Invalid array declarations


int Num = 30;
On most systems
float Data[Num]; you can not use an
integer variable
int List[31.75];

You can not use


floats to specify
the array size

CP 123: Introduction to High Level Programming


DECLARING ARRAYS
 The total number of bytes in memory for an array is given
by (number of elements in array) * (number of bytes for
each element)

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

CP 123: Introduction to High Level Programming


ARRAY ACCESS
 To access an array element, we need to give name of
variable and the location of desired element

 In C++ arrays are always zero indexed 0..N-1


 The first array element is at location 0
 The last array element is at location N-1

CP 123: Introduction to High Level Programming


ARRAY ACCESS

// Valid array access


const int SIZE = 100;
float Data[SIZE];

Data[31] = 7;
These array indices are
Total = Total + Data[20]; all in the 0..99 range
cout << Data[0];

CP 123: Introduction to High Level Programming


ARRAY ACCESS

// Invalid array access


The array index
Data[4.3] = 28;
can not be a float

Data[-8] = 0.0;
Data[200] ++; Run time errors may
… occur if array index is
outside 0..99 range
cin >> Data;
cout << Data;
We can not read
or write a whole
array at one time
CP 123: Introduction to High Level Programming
ARRAY
INITIALIZATION
 It is always important to initialize arrays before use
 Using an uninitialized variable causes major bugs
 Arrays are supposed to be initialized to 0 by default
 Sadly, this is not true for all C++ compilers

 We can store initial values in an array at declaration time


 Give collection of N values to store in array of size N
 If fewer than N values are given, the rest are set to 0
 Assign an array of same size and data type

CP 123: Introduction to High Level Programming


ARRAY
INITIALIZATION
// Valid array initialization
const int SIZE = 10;
int Value[SIZE] = {3,1,4,1,5,9,2,6,5,3};
int copy[SIZE] = Value; The rest of this array
is initialized to 0

char Name[SIZE] = {'J', 'O', 'H', 'N'};
...
float Scores[] = {93.5, 92.0, 90.1, 85.7, 83.3, 76.5};

Size of this array is determined


by number of values to right (6)
CP 123: Introduction to High Level Programming
ARRAY
INITIALIZATION

// Invalid array initialization


The Value array contains
float Data[20] = Value;
10 integers which does
… not match Data
int Numbers[5] = {2,1,4,1,5,1,6};

The number of initial values


can not be greater than the
array size

CP 123: Introduction to High Level Programming


ARRAYS AND LOOPS
 It is very natural to use loops to process arrays
 Read input values into an array
 Write output values from an array
 Calculate total of values in array

 We must take care to stay within array bounds


 Never use index less than 0
 Never use index greater than N-1
 Errors may cause “memory segmentation fault”

CP 123: Introduction to High Level Programming


ARRAYS AND LOOPS
// Input output example
int Data[10];

for (int i = 0; i < 10; i++)


cin >> Data[i];
for (int i = 0; i < 10; i++)
cout << Data[9-i];

CP 123: Introduction to High Level Programming


ARRAYS AND LOOPS
// Totaling example
const int SIZE = 10;
int Value[SIZE] = {3,1,4,1,5,9,2,6,5,3};

float Total = 0.0;


for (int pos = 0; pos < SIZE; pos++)
Total += Value[pos];
float Average = Total / SIZE;

CP 123: Introduction to High Level Programming


SUMMARY
 In this section, we saw how to declare, initialize and
access arrays in C++
 We also saw how loops could be used to read/write and
process arrays in different ways
 Next, we discussed how arrays can be used to store and
process a variable number of elements

CP 123: Introduction to High Level Programming


ARRAYS

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

CP 123: Introduction to High Level Programming


SEARCHING ARRAYS
 Linear search is the most basic algorithm for searching
 Start at beginning of array (index 0)
 Look at each element of array one at a time
 Check if we have have found what we are looking for
 Stop at end of the array (index N-1)
 This process is typically implemented with a loop

CP 123: Introduction to High Level Programming


SEARCHING ARRAYS
// Linear searching for special value
float Special = 42;
Loop over all
for (int Pos = 0; Pos < SIZE; Pos++)
array locations
{
if (Value[Pos] == Special) Check for desired
value in array
cout << "found value " << Special
<< " at position " << Pos << endl;
}

CP 123: Introduction to High Level Programming


SEARCHING ARRAYS
// Linear searching for max and min values
float Minimum = Value[0]; Initialize our best
guess of min/max
float Maximum = Value[0];
Loop over all
for (int Pos = 0; Pos < SIZE; Pos++) array locations
{
if (Value[Pos] < Minimum)
Minimum = Value[Pos]; Update values of
min/max as needed
if (Value[Pos] > Maximum)
Maximum = Value[Pos];
}

CP 123: Introduction to High Level Programming


BINARY SEARCH
 What happens if we are given an array with sorted values?
 Now we know exactly where min/max should be
 Minimum value always at location 0
 Maximum value always at location N-1

2 3 5 5 6 7 8 9

min max

CP 123: Introduction to High Level Programming


BINARY SEARCH
 The binary search algorithm can be used to search a
sorted array for a specific value
 Look at middle element of sorted array
 If equal to desired value, you found it
 If less than desired value, search right half of array
 If greater than desired value, search left half of array
 Repeat until data is found (or no data left to search)

CP 123: Introduction to High Level Programming


BINARY SEARCH
 Search for value 7 in sorted array below

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

 5 < 7, so search to right

2 3 5 5 6 7 8 9

 This cuts size of array we are searching in half

CP 123: Introduction to High Level Programming


BINARY SEARCH
 Search for value 7 in unsearched array below

2 3 5 5 6 7 8 9

 Look at middle location (4+7)/2 = 5, which contains 7

2 3 5 5 6 7 8 9

 We found the desired value in only 2 searching steps!

CP 123: Introduction to High Level Programming


BINARY SEARCH
 Search for value 2 in sorted array below

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

 5 > 2, so search to left

2 3 5 5 6 7 8 9

 This cuts size of array we are searching in half

CP 123: Introduction to High Level Programming


BINARY SEARCH
 Search for value 2 in unsearched array below

2 3 5 5 6 7 8 9

 Look at middle location (0+2)/2 = 1, which contains 3

2 3 5 5 6 7 8 9

 3 > 2, so search to left

2 3 5 5 6 7 8 9

 Now there is only one location to search!

CP 123: Introduction to High Level Programming


BINARY SEARCH
 Search for value 2 in unsearched array below

2 3 5 5 6 7 8 9

 Look at middle location (0+0)/2 = 0, which contains 2

2 3 5 5 6 7 8 9

 We found the desired value in only 3 searching steps!

CP 123: Introduction to High Level Programming


BINARY SEARCH
 This divide and conquer approach is very fast since the
array we are searching is cut in half at each step
 Consider an array with 1024 sorted values
 Searching we go from 1024 => 512 => 256 =>
128 => 64 => 32 => 16 => 8 => 4 => 2 => 1
 Only 10 steps to search array of 1024 elements

 In general, binary search takes log2N steps to search a


sorted array of N elements
 ~20 steps to search array of 1,000,000 elements
 ~30 steps to search array of 1,000,000,000 elements

CP 123: Introduction to High Level Programming


BINARY SEARCH
 To implement binary search we need to:
 Keep track of the portion of the array we are searching
 Min = smallest array index of unsearched portion
 Max = largest array index of unsearched portion
 Mid = (Min + Max) / 2 is middle position
 We need to initialize Min=0 and Max=N-1
 We need to update these values as we search

 This can be implemented using iteration or using recursion

CP 123: Introduction to High Level Programming


BINARY SEARCH
// Iterative binary search
int Search(int Desired, int Data[], int Min, int Max)
{
// Search array using divide and conquer approach
int Mid = (Min + Max) / 2;
while ((Data[Mid] != Desired) && (Max >= Min))
{ This loop will end
when data is found
// Change min to search right half or no locations are
if (Data[Mid] < Desired) left to search

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;

We change upper array index


// Update mid location here to be 1 to left of midpoint
Mid = (Min + Max) / 2;
}

CP 123: Introduction to High Level Programming


BINARY SEARCH

// Return results of search
if (Data[Mid] == Desired)
return(Mid);
else
This returns the array
return(-1); index of desired data
} value or -1 if not found

CP 123: Introduction to High Level Programming


BINARY SEARCH
// Recursive binary search
int Search( int Desired, int Data[], int Min, int Max )
{
// Terminating conditions
int Mid = (Min + Max ) / 2;
if (Max < Min)
return(-1); This returns the array
index of desired data
else if (Data[Mid] == Desired)
value or -1 if not found
return(Mid);

CP 123: Introduction to High Level Programming


BINARY SEARCH

// Recursive call to search right half
else if (Data[Mid] < Desired)
return( Search( Desired, Data, Mid+1, Max ) );
Notice how we
search a smaller
// Recursive call to search left half part of the array
with each recursive
else if (Data[Mid] > Desired)
function call
return( Search( Desired, Data, Min, Mid-1 ) );
}

CP 123: Introduction to High Level Programming


ARRAY SORTING
 The basic idea of array sorting is to move data values in
the array so they are in numerical or alphabetical order

 There are many applications that need sorted arrays


 Output array in ascending or descending order
 Search array more efficiently using binary search

 There are many algorithms for sorting arrays


 Some are easy to implement, others more complex
 Some have fast run times, others are slower

CP 123: Introduction to High Level Programming


ARRAY SORTING
 One easy algorithm to implement is selection sort
 Divide the array into two parts: sorted and unsorted
 Find smallest value in the unsorted part of array
 Swap value into end of sorted part of array
 Repeat this process until the whole array is sorted

 Consider an array containing the first 8 digits of PI


 Lets see what happens if we use selection sort
 We show the array contents after each data swap

CP 123: Introduction to High Level Programming


ARRAY SORTING

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

CP 123: Introduction to High Level Programming


ARRAY SORTING

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

CP 123: Introduction to High Level Programming


ARRAY SORTING

1 1 2 3 4 5 6 9

sorted - unsorted

 The array is sorted when the unsorted part is empty!


 In general, selection sort will take N “find minimum and
swap iterations” to sort an array of N elements
 Each “find minimum value” step looks at N data values,
so selection sort takes N2 operations

CP 123: Introduction to High Level Programming


ARRAY SORTING
// Initialize data to sort
const int SIZE = 10;
int Data[SIZE] = {3,1,4,1,5,9,2,6,5,3};

// Print unsorted data


for (int Index = 0; Index < SIZE; Index++)
cout << Index << " " << Data[Index] << endl;

CP 123: Introduction to High Level Programming


ARRAY SORTING
// Perform selection sort algorithm
This loop executes N
for (int Index = 0; Index < SIZE; Index++) times moving the
sorted-unsorted line
{
// Find smallest value in unsorted part
int SmallPos = Index; This loop executes N
for (int Pos = Index; Pos < SIZE; Pos++) times to find the
smallest data value
if (Data[Pos] < Data[SmallPos])
SmallPos = Pos;
… Notice that we start this
loop at the beginning of
the unsorted part of array

CP 123: Introduction to High Level Programming


ARRAY SORTING

// Swap smallest value into sorted part
int SmallVal = Data[SmallPos];
Data[SmallPos] = Data[Index];
Data[Index] = SmallVal;
}

// Print sorted data


for (int Index = 0; Index < SIZE; Index++)
cout << Index << " " << Data[Index] << endl;

CP 123: Introduction to High Level Programming


SUMMARY
 In this section, we described how linear search can be
used to find the min/max or special values in an array
 Then, we described how binary search can be used to
very quickly search for values in a sorted array
 Next, we introduced the “selection sort” algorithm and
showed how it can be used to sort data
 Finally, we saw how a sorted array can be used to
calculate the median value

CP 123: Introduction to High Level Programming

You might also like