0% found this document useful (0 votes)
18 views99 pages

07slide (SingleDimensionalArray)

Uploaded by

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

07slide (SingleDimensionalArray)

Uploaded by

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

Chapter 7 Single-Dimensional

Arrays and C-Strings

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


1
Opening Problem
Read one hundred numbers, compute their
average, and find out how many numbers are
above the average.

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


2
Objectives
To describe why an array is necessary in programming (§7.1).
To declare arrays (§7.2.1).
To access array elements using indexes (§7.2.2).
To initialize the values in an array (§7.2.3).
To program common array operations (displaying arrays, summing all elements, finding
min and max elements, random shuffling, shifting elements) (§7.2.4).
To simplify programming using the foreach loops (<LINK>§7.2.5</LINK>).
To apply arrays in application development (AnalyzeNumbers, DeckOfCards) (§§7.3–
7.4).
To define and invoke functions with array arguments (§7.5).
To define a const array parameter to prevent it from being changed (§7.6).
To return an array by passing it as an argument (§7.7).
To count occurrences of each letter in an array of characters (CountLettersInArray)
(§7.8).
To search elements using the linear (§7.9.1) or binary search algorithm (§7.9.2).
To sort an array using the selection sort (§7.10).
To represent strings using C-strings and use C-string functions (§7.11).
To convert a number to a string using the C++11’s to_string function (§7.12).
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
3
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
double myList [10];

myList[0] 5.6
myList[1] 4.5
myList[2] 3.3
myList[3] 13.2
myList[4] 4.0
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34.0

myList[7] 45.45

myList[8] 99.993

myList[9] 111.23

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


4
Declaring Array Variables
datatype arrayName[arraySize];
Example:
double myList[10];

C++ requires that the array size used to declare an array must be a
constant expression. For example, the following code is illegal:
int size = 4;
double myList[size]; // Wrong
But it would be OK, if size is a constant as follow:
const int size = 4;
double myList[size]; // Correct

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


5
Arbitrary Initial Values
When an array is created, its elements are assigned
with arbitrary values.

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


6
Indexed Variables
The array elements are accessed through the index. Array
indices are 0-based; that is, they start from 0 to arraySize-1.
In the example in Figure 7.1, myList holds ten double
values and the indices are from 0 to 9.

Each element in the array is represented using the


following syntax, known as an indexed variable:

arrayName[index];

For example, myList[9] represents the last element in the


array myList.
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
7
Using Indexed Variables
After an array is created, an indexed variable can
be used in the same way as a regular variable.
For example, the following code adds the value
in myList[0] and myList[1] to myList[2].

myList[2] = myList[0] + myList[1];

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


8
No Bound Checking
C++ does not check array’s boundary. So, accessing
array elements using subscripts beyond the
boundary (e.g., myList[-1] and myList[11]) does not
does cause syntax errors, but the operating system
might report a memory access violation.

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


9
Array Initializers
Declaring, creating, initializing in one step:
dataType arrayName[arraySize] = {value0, value1,
..., valuek};

double myList[4] = {1.9, 2.9, 3.4, 3.5};

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


10
Declaring, creating, initializing
Using the Shorthand Notation
double myList[4] = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the
following statements:

double myList[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


11
CAUTION
Using the shorthand notation, you
have to declare, create, and initialize
the array all in one statement.
Splitting it would cause a syntax
error. For example, the following is
wrong:
double myList[4];
myList = {1.9, 2.9, 3.4, 3.5};
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
12
Implicit Size
C++ allows you to omit the array size when
declaring and creating an array using an initilizer.
For example, the following declaration is fine:

double myList[] = {1.9, 2.9, 3.4, 3.5};

C++ automatically figures out how many elements


are in the array.

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


13
Partial Initialization
C++ allows you to initialize a part of the array. For
example, the following statement assigns values
1.9, 2.9 to the first two elements of the array. The
other two elements will be set to zero. Note that if
an array is declared, but not initialized, all its
elements will contain “garbage”, like all other local
variables.

double myList[4] = {1.9, 2.9};

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


14
Initializing arrays with random
values
The following loop initializes the array myList with
random values between 0 and 99:

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


{
myList[i] = rand() % 100;
}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


15
animation
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values

int main()
{ After the array is created

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 0
{ 2 0

values[i] = values[i] + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


16
animation
Trace Program with Arrays
i becomes 1

int main()
{
After the array is created
int values[5];
for (int i = 1; i < 5; i++) 0 0

{ 1 0

0
values[i] = values[i] + values[i-1]; 2

3 0
} 0
4
values[0] = values[1] + values[4];
}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


17
animation
Trace Program with Arrays
i (=1) is less than 5

int main()
{
After the array is created
int values[5];
for (int i = 1; i < 5; i++) 0 0
{ 1 0

values[i] = values[i] + values[i-1]; 2 0

} 3 0

0
values[0] = values[1] + values[4]; 4

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


18
animation
Trace Program with Arrays
After this line is executed, value[1] is 1

int main()
{ After the first iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 0

values[i] = values[i] + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


19
animation

Trace Program with Arrays


After i++, i becomes 2

int main()
{
int values[5]; After the first iteration

for (int i = 1; i < 5; i++) 0 0

{ 1 1

0
2
values[i] = values[i] + 3 0

values[i-1]; 4 0

}
values[0] = values[1] +
values[4];
}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


20
animation
Trace Program with Arrays
i (= 2) is less than 5
int main()
{
int values[5];
for (int i = 1; i < 5; i++) After the first iteration

{ 0 0

values[i] = values[i] + 1 1

values[i-1]; 2 0

3 0
} 0
4
values[0] = values[1] +
values[4];
}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


21
animation
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)

int main()
{ After the second iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = values[i] + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


22
animation
Trace Program with Arrays
After this, i becomes 3.

int main()
{ After the second iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = values[i] + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


23
animation
Trace Program with Arrays
i (=3) is still less than 5.

int main()
{ After the second iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = values[i] + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


24
animation
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)

int main()
{ After the third iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = values[i] + values[i-1]; 3 6

} 4 0

values[0] = values[1] + values[4];


}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


25
animation
Trace Program with Arrays
After this, i becomes 4

int main()
{ After the third iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = values[i] + values[i-1]; 3 6

} 4 0

values[0] = values[1] + values[4];


}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


26
animation
Trace Program with Arrays
i (=4) is still less than 5

int main()
{ After the third iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = values[i] + values[i-1]; 3 6

} 4 0

values[0] = values[1] + values[4];


}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


27
animation
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)

int main()
{ After the fourth iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3

values[i] = values[i] + values[i-1]; 3 6

} 4 10

values[0] = values[1] + values[4];


}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


28
animation
Trace Program with Arrays
After i++, i becomes 5

int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{ After the fourth iteration
values[i] = values[i] + values[i-1];
} 0 0
values[0] = values[1] + values[4]; 1 1
} 2 3

3 6

4 10

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


29
animation

Trace Program with Arrays


i ( =5) < 5 is false. Exit the loop

int main()
{
int values[5];
for (int i = 1; i < 5; i++) After the fourth iteration
{
0
values[i] = values[i] + values[i-1]; 0

1 1
} 2 3

values[0] = values[1] + values[4]; 3 6

} 4 10

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


30
animation
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)

int main()
{
int values[5];
for (int i = 1; i < 5; i++) 0 11

{ 1 1

values[i] = values[i] + values[i-1]; 2 3

} 3 6

values[0] = values[1] + values[4]; 4 10

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


31
Printing arrays
To print an array, you have to print each element in the
array using a loop like the following:

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


{
cout << myList[i] << " ";
}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


32
Copying Arrays
Can you copy array using a syntax like this?
list = myList;

This is not allowed in C++. You have to copy individual


elements from one array to the other as follows:

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


{
list[i] = myList[i];
}
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
33
Summing All Elements
Use a variable named total to store the sum. Initially total
is 0. Add each element in the array to total using a loop
like this:

double total = 0;
for (int i = 0; i < ARRAY_SIZE; i++)
{
total += myList[i];
}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


34
Finding the Largest Element
Use a variable named max to store the largest element.
Initially max is myList[0]. To find the largest element in
the array myList, compare each element in myList with
max, update max if the element is greater than max.

double max = myList[0];


for (int i = 1; i < ARRAY_SIZE; i++)
{
if (myList[i] > max) max = myList[i];
}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


35
Finding the smallest index of the
largest element
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < ARRAY_SIZE; i++)
{
if (myList[i] > max)
{
max = myList[i];
indexOfMax = i;
}
}
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
36
Random Shuffling

srand(time(0));
for (int i = 0; i < ARRAY_SIZE; i++)
{
// Generate an index randomly
int index = rand() % ARRAY_SIZE;
double temp = myList[i];
myList[i] = myList[index];
myList[index] = temp;
}
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
37
Shifting Elements

double temp = myList[0]; // Retain the first element


// Shift elements left
for (int i = 1; i < myList.length; i++)
{
myList[i - 1] = myList[i];
}
// Move the first element to fill in the last position
myList[myList.length - 1] = temp;

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


38
Foreach Loops

for (double e: myList) {


cout << e << endl;
}

C++11: Foreach loops


are defined in C++11

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


39
Analyze Numbers
Read one hundred numbers, compute their
average, and find out how many numbers are
above the average.

AnalyzeNumbers

AnalyzeNumbers

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


40
supplement

Problem: Lotto Numbers


Your grandma likes to play the Pick-10 lotto. Each
ticket has 10 unique numbers ranging from 1 to 99.
Every time she buys a lot of tickets. She likes to
have her tickets to cover all numbers from 1 to 99.
Write a program that reads the ticket numbers from
a file and checks whether all numbers are covered.
Assume the last number in the file is 0.
LottoNumbers

LottoNumbers

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


41
Problem: Deck of Cards
The problem is to write a program that picks four cards randomly
from a deck of 52 cards. All the cards can be represented using an
array named deck, filled with initial values 0 to 52, as follows:

int deck[52];
// Initialize cards
for (int i = 0; i < NUMBER_OF_CARDS; i++)
deck[i] = i;

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


42
Problem: Deck of Cards, cont.
deck deck
0 [0] 0 [0] 6 Card number 6 is
. . .
. 13 Spades (♠) . .
[1] 48 5 of Spades
[2] 11
. . . [3] 24
12 [12] 12 Card number 48 is
[4] .
13 [13] 13 10 of Clubs
[5] .
. . . .
13 Hearts (♥)
. .
. . . .
. . . Card number 11 is
Random shuffle . .
25 [25] 25 Queen of Spades
[25] .
26 [26] 26 [26] .
. . .
13 Diamonds (♦)
. .
. . . Card number 24 is
. .
. . . Queen of Hearts
. .
38 [38] 38 [38] .
39 [39] 39 [39] .
. . . . .
. 13 Clubs (♣) . . . .
. . . . .
51 [51] 51 [51] .
DeckOfCards

DeckOfCards

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


43
Passing Arrays to Functions
Just as you can pass single values to a function,
you can also pass an entire array to a function.
Listing 7.3 gives an example to demonstrate how
to declare and invoke this type of functions.

PassArrayDemo

PassArrayDemo

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


44
Passing Size along with Array
Normally when you pass an array to a function, you
should also pass its size in another argument. So the
function knows how many elements are in the array.
Otherwise, you will have to hard code this into the
function or declare it in a global variable. Neither is
flexible or robust.

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


45
Pass-by-Value
Passing an array variable means that the starting
address of the array is passed to the formal
parameter by value. The parameter inside the
function references to the same array that is passed
to the function. No new arrays are created.

EffectOfPassArrayDemo

EffectOfPassArrayDemo

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


46
const Parameters
Passing arrays by reference makes sense for performance
reasons. If an array is passed by value, all its elements must
be copied into a new array. For large arrays, it could take
some time and additional memory space. However, passing
arrays by its reference value could lead to errors if your
function changes the array accidentally. To prevent it from
happening, you can put the const keyword before the array
parameter to tell the compiler that the array cannot be
changed. The compiler will report errors if the code in the
function attempts to modify the array.

ConstArrayDemo

ConstArrayDemo Compile error


© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
47
Returning an Array from a Function
Can you return an array from a function using a similar
syntax? For example, you may attempt to declare a function
that returns a new array that is a reversal of an array as
follows:

// Return the reversal of list


int[] reverse(const int list[], int size)

This is not allowed in C++.

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


48
Modifying Arrays in Functions, cont.
However, you can circumvent this restriction by passing
two array arguments in the function, as follows:
// newList is the reversal of list
void reverse(const int list[], int newList[], int size)

list

newList

ReverseArray

ReverseArray

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


49
animation

Trace the reverse Function


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 0

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


50
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);
i = 0 and j = 5

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 0

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


51
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2); i (= 0) is less than 6

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 0

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


52
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i = 0 and j = 5
} Assign list[0] to result[5]
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


53
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; After this, i becomes 1 and j
} becomes 4
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


54
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

i (=1) is less than 6


void reverse(const int list[], int newList[], int size)
{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


55
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i = 1 and j = 4
Assign list[1] to result[4]
}
list 1 2 3 4 5 6

newList 0 0 0 0 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


56
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} After this, i becomes 2 and
j becomes 3
}

list 1 2 3 4 5 6

newList 0 0 0 0 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


57
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i (=2) is still less than 6
}
}

list 1 2 3 4 5 6

newList 0 0 0 0 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


58
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i = 2 and j = 3
Assign list[i] to result[j]
}

list 1 2 3 4 5 6

newList 0 0 0 3 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


59
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; After this, i becomes 3 and
} j becomes 2

list 1 2 3 4 5 6

newList 0 0 0 3 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


60
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i (=3) is still less than 6
}

list 1 2 3 4 5 6

newList 0 0 0 3 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


61
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i = 3 and j = 2
Assign list[i] to result[j]
}

list 1 2 3 4 5 6

newList 0 0 4 3 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


62
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} After this, i becomes 4 and
} j becomes 1

list 1 2 3 4 5 6

newList 0 0 4 3 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


63
animation

Trace the reverse Function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i (=4) is still less than 6
}

list 1 2 3 4 5 6

newList 0 0 4 3 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


64
animation

Trace the reverse Function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
i = 4 and j = 1
newList[j] = list[i]; Assign list[i] to result[j]
}
}

list 1 2 3 4 5 6

newList 0 5 4 3 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


65
animation

Trace the reverse Function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} After this, i becomes 5 and
j becomes 0
}

list 1 2 3 4 5 6

newList 0 5 4 3 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


66
animation

Trace the reverse Function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i (=5) is still less than 6
}

list 1 2 3 4 5 6

newList 0 5 4 3 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


67
animation

Trace the reverse Function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i = 5 and j = 0
Assign list[i] to result[j]
}

list 1 2 3 4 5 6

newList 6 5 4 3 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


68
animation

Trace the reverse Function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
After this, i becomes 6 and
} j becomes -1
}

list 1 2 3 4 5 6

newList 6 5 4 3 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


69
animation

Trace the reverse function, cont.


int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i (=6) < 6 is false. So exit
} the loop.

list 1 2 3 4 5 6

newList 6 5 4 3 2 1

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


70
Problem: Counting Occurrence of Each
Letter

Generate 100 lowercase


chars[0] counts[0]
letters randomly and assign chars[1] counts[1]

to an array of characters. … … … …
… … … …
Count the occurrence of each chars[98] counts[24]
letter in the array. chars[99] counts[25]

CountLetterInArray

CountLetterInArray

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


71
Searching Arrays
Searching is the process of looking for a specific element in
an array; for example, discovering whether a certain score is
included in a list of scores. Searching is a common task in
computer programming. There are many algorithms and data
structures devoted to searching. In this section, two
commonly used approaches are discussed, linear search and
binary search.
int linearSearch(const int list[], int key, int arraySize)
{ LinearSearch

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


{ LinearSearch
if (key == list[i])
return i; [0] [1] [2] …
} list
return -1; key Compare key with list[i] for i = 0, 1, …
}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


72
Linear Search
The linear search approach compares the key
element, key, sequentially with each element in
the array list. The Function continues to do so
until the key matches an element in the list or
the list is exhausted without a match being
found. If a match is made, the linear search
returns the index of the element in the array
that matches the key. If no match is found, the
search returns -1.

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


73
animation

Linear Search Animation


Key List
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8

3 6 4 1 9 7 3 2 8
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
74
animation
Linear Search Animation
liveexample.pearsoncmg.com/dsanimation/LinearSearche
Book.html

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


75
From Idea to Solution
int linearSearch(const int list[], int key, int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
if (key == list[i])
return i; [0] [1] [2] …
} list
return -1; key Compare key with list[i] for i = 0, 1, …
}

Trace the function


int[] list = {1, 4, 4, 2, 5, -3, 6, 2};
int i = linearSearch(list, 4); // returns 1
int j = linearSearch(list, -4); // returns -1
int k = linearSearch(list, -3); // returns 5

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


76
Binary Search
For binary search to work, the elements in the
array must already be ordered. Without loss of
generality, assume that the array is in
ascending order.
e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79
The binary search first compares the key with
the element in the middle of the array.
BinarySearch

BinarySearch

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


77
Binary Search, cont.
Consider the following three cases:
If the key is less than the middle element,
you only need to search the key in the first
half of the array.
If the key is equal to the middle element,
the search ends with a match.
If the key is greater than the middle
element, you only need to search the key in
the second half of the array.
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
78
animation

Binary Search

Key List

8 1 2 3 4 6 7 8 9
8 1 2 3 4 6 7 8 9

8 1 2 3 4 6 7 8 9

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


79
animation
Binary Search Animation
http://liveexample.pearsoncmg.com/dsanimation/BinarySe
archeBook.html

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


80
Binary Search, cont.
key is 11 low mid high

key < 50 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
list 2 4 7 10 11 45 50 59 60 66 69 70 79
low mid high

[0] [1] [2] [3] [4] [5]


key > 7 list 2 4 7 10 11 45

low mid high

[3] [4] [5]


key == 11 list 10 11 45

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


81
key is 54 Binary
low Search,midcont. high

key > 50 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
list 2 4 7 10 11 45 50 59 60 66 69 70 79
low mid high

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
key < 66 list 59 60 66 69 70 79

low mid high

[7] [8]
key < 59 list 59 60

low high

[6] [7] [8]


59 60
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
82
Binary Search, cont.
The binarySearch Function returns the index of the
search key if it is contained in the list. Otherwise,
it returns –insertion point - 1. The insertion point is
the point at which the key would be inserted into
the list.

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


83
From Idea to Solution
int binarySearch(const int list[], int key, int arraySize)
{
int low = 0;
int high = arraySize - 1;

while (high >= low)


{
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}

return –low - 1;
}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


84
Sorting Arrays
Sorting, like searching, is also a common task in
computer programming. It would be used, for
instance, if you wanted to display the grades from in
alphabetical order. Many different algorithms have
been developed for sorting. This section introduces
selection sort.

SelectionSort

SelectionSort

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


85
Selection Sort
Selection sort finds the largest number in the list and places it last. It then finds
the largest number remaining and places it next to last, and so on until the list
contains only a single number.
swap

Select 1 (the smallest) and swap it 2 9 5 4 8 1 6


with 2 (the first) in the list
swap
The number 1 is now in the
Select 2 (the smallest) and swap it 1 9 5 4 8 2 6 correct position and thus no
with 9 (the first) in the remaining longer needs to be considered.
list swap

The number 2 is now in the


Select 4 (the smallest) and swap it 1 2 5 4 8 9 6 correct position and thus no
with 5 (the first) in the remaining longer needs to be considered.
list
The number 6 is now in the
5 is the smallest and in the right 1 2 4 5 8 9 6 correct position and thus no
position. No swap is necessary longer needs to be considered.
swap
The number 5 is now in the
Select 6 (the smallest) and swap it 1 2 4 5 8 9 6 correct position and thus no
with 8 (the first) in the remaining longer needs to be considered.
list swap

The number 6 is now in the


Select 8 (the smallest) and swap it 1 2 4 5 6 9 8 correct position and thus no
with 9 (the first) in the remaining longer needs to be considered.
list

The number 8 is now in the


Since there is only one element 1 2 4 5 6 8 9 correct position and thus no
remaining in the list, sort is longer needs to be considered.
completed

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


86
animation
Selection Sort Animation
http://liveexample.pearsoncmg.com/dsanimation/Selection
SorteBook.html

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


87
From Idea to Solution
for (int i = 0; i < listSize; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

...

list[0] list[1] list[2] list[3] ... list[10]

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


88
for (int i = 0; i < listSize; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i; j < listSize; j++)
{
if (currentMin > list[j])
{
currentMin = list[j];
currentMinIndex = j;
}
}
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
89
for (int i = 0; i < listSize; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i; j < listSize; j++)
{
if (currentMin > list[j])
{
currentMin = list[j];
currentMinIndex = j;
}
}
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
90
for (int i = 0; i < listSize; i++)
{
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
if (currentMinIndex != i)
{
list[currentMinIndex] = list[i];
list[i] = currentMin;
}

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


91
Optional
How to Insert?

The insertion sort [0] [1] [2] [3] [4] [5] [6]
algorithm sorts a list list 2 5 9 4 Step 1: Save 4 to a temporary variable currentElement

of values by [0] [1] [2] [3] [4] [5] [6]


repeatedly inserting list 2 5 9 Step 2: Move list[2] to list[3]
an unsorted element [0] [1] [2] [3] [4] [5] [6]
into a sorted sublist list 2 5 9 Step 3: Move list[1] to list[2]
until the whole list
[0] [1] [2] [3] [4] [5] [6]
is sorted. list 2 4 5 9 Step 4: Assign currentElement to list[1]

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


92
Initializing Character Arrays
char city[] = {'D', 'a', 'l', 'l', 'a', 's'};

char city[] = "Dallas";


This statement is equivalent to the preceding statement,
except that C++ adds the character '\0', called the null
terminator, to indicate the end of the string. Recall that a
character that begins with the back slash symbol (\) is an
escape character.

'D' 'a' 'l' 'l' 'a' 's' '\0'


city[0] city[1] city[2] city[3] city[4] city[5] city[6]

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


93
Reading C-Strings
You can read a string from the keyboard using the
cin object. For example, see the following code:

char city[10];
cout << "Enter a city: ";
cin >> city; // read to array city
cout << "You entered " << city << endl;

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


94
Printing Character Array
For a character array, it can be printed using one print
statement. For example, the following code displays
Dallas:

char city[] = "Dallas";


cout << city;

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


95
Reading C-Strings Using getline
C++ provides the cin.getline function in the iostream
header file, which reads a string into an array. The syntax
of the function is:

cin.getline(char array[], int size, char delimitChar)

The function stops reading characters when the delimiter


character is encountered or when the size - 1 number of
characters are read. The last character in the array is
reserved for the null terminator ('\0'). If the delimiter is
encountered, it is read, but not stored in the array. The
third argument delimitChar has a default value ('\n').
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
96
Function Description

size_t strlen(const char s[])


C-String Returns the length of the string, i.e., the number of the
characters before the null terminator.
strcpy(char s1[], const char s2[])
Functions Copies string s2 to string s1.
strncpy(char s1[], const char s2[], size_t n)
Copies the first n characters from string s2 to string s1.
strcat(char s1[], const char s2[])
Appends string s2 to s1.
strncat(char s1[], const char s2[], size_t n)
Appends the first n characters from string s2 to s1.
int strcmp(char s1[], const char s2[])
Returns a value greater than 0, 0, or less than 0 if s1 is greater
than, equal to, or less than s2 based on the numeric code of the
characters.
int strncmp(char s1[], const char s2[], size_t n)
Same as strcmp, but compares up to n number of characters in s1
with those in s2.
int atoi(char s[])
Returns an int value for the string.
double atof(char s[])
Returns a double value for the string.
long atol(char s[])
Returns a long value for the string.
void itoa(int value, char s[], int radix)
Obtains an integer value to a string based on specified radix.

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


97
String Examples
CopyString

CopyString
CombineString

CombineString
CompareString

CompareString
StringConversion

StringConversion

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


98
Converting Numbers to Strings
int x = 15;
double y = 1.32;
long long int z = 10935;
string s = "Three numbers: " + to_string(x) + ", " +
to_string(y) + ", and " + to_string(z);
cout << s << endl;

C++11: the to_string function


is defined in C++11

© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.


99

You might also like