Module 6 - Guidance Notes
Module 6 - Guidance Notes
ARRAYS
3
What are we going to learn?
• Array
• Passing array elements to functions
• Passing array to functions
• Searching / sorting an array
• Two dimensional arrays
• 2D array as function parameters
• char & char array
4
Handling Data of the Same Type
• Very often, a program needs to handle a collection of
data of the same type
• Consider the following problem:
– Write a program to input the scores of 80 students in a
class and compute their average score and output those
scores that are lower than the average.
int score_01, score_02, score_03, score_04, …, score_80;
Using individually
cin >> score_01 >> score_02 >> … >> score_80; named variables to
double average = (score_01 + score_02 + … + score_80) / 80.0; handle such data is
if (score_01 < average) cout << score_01 << endl; cumbersome,
if (score_02 < average) cout << score_02 << endl; especially for large
… datasets
if (score_80 < average) cout << score_80 << endl;
5
Arrays
• Arrays in C++ provide a convenient way to process
such data Main memory
-46 7 0 23 2048 -2 1 78 99
7
Indexes of Array Elements
• Array indexes always start from zero and end with the
integer that is one less than the size of the array.
c[0] c[1] c[2] c[3] c[4] c[5]
size of c is 6
-46 7 0 23 2048 -2 elements are c[0], c[1], c[2], c[3], c[4], c[5]
c[1] = 100;
cout << c[0] + c[1] + c[2] << endl;
int x = c[6] / 2;
int a = 1, b = 2;
c[a + b] += 2; // c[3] = c[3] + 2
int i = 4;
c[i + 1] = c[i] − 30; // c[5] = c[4] − 30
8
Indexes of Array Elements
• The compiler will NOT report any Main memory
100 score[1]
84 score[3]
52 score[4]
52 score[2]
size equals 3
11
Initialization with Initializer List
• The compiler will report an error if too many values are
given in the initialization, e.g.,
int score[5] = {80, 100, 63, 84, 52, 96};
✗
• It is, however, legal to provide fewer values than the
number of elements in the initialization.
– Those values will be used to initialize the first few elements.
– The remaining elements will be initialized to a zero of the array
base type.
80 score[0]
100 score[1]
int score[5] = {80, 100};
0 score[2]
0 score[3]
✗
score = { 80, 100, 63, 84, 52 };
score[] = { 80, 100, 63, 84, 52 };
score[5] = { 80, 100, 63, 84, 52 };
13
Example: Print the contents of an array with a loop
Need this library for setw()
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// use initializer list to initialize array n
int n[10] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
return 0;
}
Using a loop to setw(): set the width (i.e., # of space) for the
access and print out next item to be printed out
each element 14
Initialization with a Loop
• Use a loop to access each element and initialize them to
some initial values.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
using the loop int n[10]; // n is an array 10 integers
control
// initialize elements of array n to 0
variable i as the
for ( int i = 0; i < 10; ++i )
index n[i] = 0; // set element at location i to 0
int main()
{
Only need to change
// constant variable can be used to specify array size
const int arraySize = 10; the value of
arraySize to make
int s[arraySize]; // array s has 10 elements the program scalable,
for (int i = 0; i < arraySize; ++i) // set the values i.e., for the program to
s[i] = 2 + 2*i; work for other array
sizes.
cout << "Element" << setw(13) << "Value" << endl;
return 0;
17
}
Example 2
• Using array elements as counters, e.g., roll a die and record the
frequency of occurrences for each side.
int frequency[ 7 ];
// ignore element 0, use elements 1, 2, …, 6 only
18
Example 2
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
const int arraySize = 7; // ignore element zero
int frequency[arraySize] = {}; // initialize elements to 0
return 0;
} 19
Optional Exercises
1. Write a program to initialize an array with the integers 1-10 and
compute the sum of the 10 numbers.
2. Write a program to initialize an array with the first 10 odd integers
starting from 1, and compute the product of the 10 numbers.
3. Write a program to initialize an array with the 10 characters ‘a’ to ‘j’
and print them out in reverse.
4. Write a program to get 10 input numbers from the users, print
them out in reverse, and print out their sum.
5. Write a program to get input integers from the user repeatedly
until the user enters 0. Your program should count the number of
1, 2, 3, 4, 5, 6 input by the user and print the frequencies out.
22
Passing Arrays to Functions
• It is also possible to pass an entire array to a function (called an array
parameter)
• To indicate that a formal parameter is an array parameter,
a pair of square brackets [ ] is placed after its identifier in
the function header and function declaration
Syntax (function header)
type_ret func_name(base_type array_para[], …)
23
Passing Arrays to Functions
• Examples
Function definition
void modifyArray( int b[], int arraySize )
{
…
}
Function call
Just need the array
int a[10];
name here; no square
modifyArray( a, 10);
brackets after the array
identifier in function call
24
Passing Arrays to Functions
25
Passing Arrays to Functions
int main()
{
const int arraySize = 5; // size of array a
int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize array a
* Note that the values of the array elements are modified by the
function, which is of a similar effect as pass-by-reference
27
Searching an Array
• A common programming task is to search an array for
a given value.
a[ 0 ] a[ 1 ] a[ 2 ] a[ 3 ] a[ 4 ] a[ 5 ] a[ 6 ] a[ 7 ] a[ 8 ]
-46 7 0 23 2048 -2 1 78 99
28
Linear Search
• The simplest method is to perform a linear search in
which the array elements are examined sequentially
from first to last
a[ 0 ] a[ 1 ] a[ 2 ] a[ 3 ] a[ 4 ] a[ 5 ] a[ 6 ] a[ 7 ] a[ 8 ]
-46 7 0 23 2048 -2 1 78 99
29
Linear Search
// linear search of key value in array[]
// return the index of first occurrence of key in array[]
// return -1 if key is not found in array[]
int linearSearch( const int array[], int sizeOfArray, int key )
{
for ( int j = 0; j < sizeOfArray; ++j )
if ( array[ j ] == key ) // if found,
return j; // return location of key
const int array[]: the const keyword is to specify that the contents of the
formal parameter array[] are to remain constant (i.e., not
to be changed) in this function.
30
Linear Search search.cpp
int main()
{
const int arraySize = 10; // size of array
int a[ arraySize ]; // declare array a
int searchKey; // value to locate in array a
return 0;
} 31
Linear Search (Variant)
• The function linearSearch() returns only the first
occurrence of the search item.
• What if we need the locations of ALL occurrences of
the search item?
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8]
-46 7 0 78 2048 -2 1 78 99
32
Linear Search (Variant)
• How to make changes to linearSearch() so that we
can make use of it to look for all occurrences of an item?
• What does linearSearch() return?
• How about if we start searching from the returned
position of a previous call of linearSearch()?
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8]
-46 7 0 78 2048 -2 1 78 99
after sorting
in ascending order
-46 -2 0 7 23 2048
35
Selection Sort
• A total of N iterations are needed to sort N elements
• At each iteration i, i = 0, …, N-1,
– exchange a[i] with the smallest item among a[i]… a[N-1] (or
the largest, if sort in descending order)
a[0] … a[i] … a[N-1]
36
: current element
37
: current element
To sort in
ascending order
38
Selection Sort
void swap(int &a, int &b)
{
// sort values in array[] in ascending order by selection sort int tmp = a;
void sort(int array[], int sizeOfArray ) a = b;
{ b = tmp;
int i, j, idx; return;
int min; }
int main()
{
const int arraySize = 6; // size of array
int a[ arraySize ] = {-2, 7, 0, 23, 2048, -46}; // declare array a
sort( a, arraySize );
cout << "Sorted array: "; void print_array( const int array[], int sizeOfArray )
print_array( a, arraySize ); {
for ( int i = 0; i < sizeOfArray; ++i )
return 0; cout << "[" << setw(2) << i << "] ";
} cout << endl;
40
Two-Dimensional Arrays
• How about a table of values arranged in rows and
columns?
• A two-dimensional array (2D array):
Column 0 Column 1 Column 2 Column 3
array_name[row_index][column_index]
41
Two-Dimensional Arrays
• To declare a 2D array:
int score_2D[5][4];
int score_2D[5][4];
score_2D[0][0] = 80;
score_2D[4][3] = score_2D[0][0] + 20;
42
Two-Dimensional Arrays
• Initialization:
int b[2][3] = { 1, 2, 3, 4, 5 };
b 0 1 2
0 1 2 3
1 4 5 0
43
Two-Dimensional Arrays
• Using a nested for loop to run through all elements.
const int nRows = 3;
const int nCols = 5;
int array2D[nRows][nCols];
int i, j;
// print out array contents
// assign initial values
for (i = 0; i < nRows; ++i)
for (i = 0; i < nRows; ++i)
{
for (j = 0; j < nCols; ++j)
for (j = 0; j < nCols; ++j)
array2D[i][j] = nCols*i + j;
cout << setw(3) << array2D[i][j] << ' ';
cout << endl; // start new line for each row
array2D.cpp }
44
2D Array as Function Parameter
• Recall that for using a 1D array as parameter:
void print_1D_array ( int array [], int sizeOfArray );
return 0;
}
Multi-Dimensional Arrays
• Arrays with two or more dimensions are known as
multi-dimensional arrays. e.g. int score_3D [5][4][3];
48
char Data Type
• Recall that the data type char is used for representing
single characters, e.g., letters, digits, special symbols.
char c1 = 'a'; // the character 'a'
char c2 = '2'; // the character '2'
char c3 = '\n'; // the newline character
49
The ASCII Character Set
Control Characters Printable Characters
0 (Null character) 32 space 64 @ 96 `
1 (Start of Header) 33 ! 65 A 97 a
2 (Start of Text) 34 " 66 B 98 b
3 (End of Text) 35 # 67 C 99 c
4 (End of Trans.) 36 $ 68 D 100 d
5 (Enquiry) 37 % 69 E 101 e
6 (Acknowledgement) 38 & 70 F 102 f
7 (Bell) 39 ' 71 G 103 g
8 (Backspace) 40 ( 72 H 104 h
9 (Horizontal Tab) 41 ) 73 I 105 i
10 (Line feed) 42 * 74 J 106 j
11 (Vertical Tab) 43 + 75 K 107 k
12 (Form feed) 44 , 76 L 108 l
13 (Carriage return) 45 - 77 M 109 m
14 (Shift Out) 46 . 78 N 110 n
15 (Shift In) 47 / 79 O 111 o
16 (Data link escape) 48 0 80 P 112 p
17 (Device control 1) 49 1 81 Q 113 q
18 (Device control 2) 50 2 82 R 114 r
19 (Device control 3) 51 3 83 S 115 s
20 (Device control 4) 52 4 84 T 116 t
21 (Negative acknowl.) 53 5 85 U 117 u
22 (Synchronous idle) 54 6 86 V 118 v
23 (End of trans. block) 55 7 87 W 119 w
24 (Cancel) 56 8 88 X 120 x
25 (End of medium) 57 9 89 Y 121 y
26 (Substitute) 58 : 90 Z 122 z
27 (Escape) 59 ; 91 [ 123 {
28 (File separator) 60 < 92 \ 124 |
29 (Group separator) 61 = 93 ] 125 }
30 (Record separator) 62 > 94 ^ 126 ~
31 (Unit separator) 63 ? 95 _
127 (Delete) 50
char and int
• Examples
Screen output
A
char c = 'A';
cout << c << endl;
Screen output
A
char c = 65;
cout << c << endl;
51
char and int
• We may use an int variable to store the value of a
char variable. In this case, the ASCII code of the char
will be stored. Screen output
A
char letter = 'A'; 65
int val = letter;
52
char and int
• Arithmetic operations between char variables indeed
operates on the ASCII values of the characters.
char letter1 = 'a'; Screen output
char letter2 = 'b';
a
cout << letter1 << endl;
b
cout << letter2 << endl;
-1
cout << letter1 – letter2 << endl; 25
cout << 'z' – 'a' << endl; a
letter2--;
cout << letter2 << endl;
53
char and int
• More examples Screen output
50
char c = '1';
int num = c + 1;
cout << num << endl;
The statement int num = c + 1 takes the ASCII value of '1' (i.e., 49)
for the addition operation.
Screen output
D
char from = 'd';
char to = from – ('a' – 'A');
cout << to << endl;
char letter;
cin >> letter;
Since the ASCII codes of the small letters and the capital letters are in
order, we may use the relational operators (<, >, <=, >=) and equality
operators (==, !=) to compare between characters.
55
Character Handling Functions
The <cctype> header file contains handy functions for character
handling. Here are some examples:
int isdigit(int c) Returns a nonzero (true) value if c is a digit, and 0 (false) otherwise
int isalpha(int c) Returns a nonzero (true) value if c is a letter, and 0 (false) otherwise
int isalnum(int c) Returns a nonzero (true) value if c is a digit or a letter, and 0 (false) otherwise
int islower(int c) Returns a nonzero (true) value if c is a lowercase letter, and 0 (false) otherwise
int isupper(int c) Returns a nonzero (true) value if c is an uppercase letter, and 0 (false) otherwise
If c is an uppercase letter, returns c as lowercase letter. Otherwise, returns the
int tolower(int c)
argument unchanged.
If c is a lowercase letter, returns c as an uppercase letter. Otherwise, returns the
int toupper(int c)
argument unchanged.
int main()
{
char a;
a = '7';
cout << a << (isdigit(a) ? " is " : " is not ") << "a digit" << endl;
a = '$';
cout << a << (isdigit(a) ? " is " : " is not ") << "a digit" << endl;
a = 'B';
cout << a << (isalpha(a) ? " is " : " is not ") << "a letter" << endl;
a = 'b';
cout << a << (isalpha(a) ? " is " : " is not ") << "a letter" << endl; charfunc.cpp
a = '4';
cout << a << (isalpha(a) ? " is " : " is not ") << "a letter" << endl;
a = 'Z';
cout << a << (islower(a) ? " is " : " is not ") << "a lowercase letter" << endl;
a = 'z';
cout << a << (islower(a) ? " is " : " is not ") << "a lowercase letter" << endl; We will rewrite
a = '5';
this program in
cout << a << (islower(a) ? " is " : " is not ") << "a lowercase letter" << endl;
C in part IV later.
a = 'M';
cout << a << (isupper(a) ? " is " : " is not ") << "an uppercase letter" << endl;
a = 'm';
cout << a << (isupper(a) ? " is " : " is not ") << "an uppercase letter" << endl;
a = '#';
cout << a << (isupper(a) ? " is " : " is not ") << "an uppercase letter" << endl;
return 0;
}
57
Character Handling Functions
Screen output of charfunc.cpp
7 is a digit
$ is not a digit
B is a letter
b is a letter
4 is not a letter
Z is not a lowercase letter
z is a lowercase letter
5 is not a lowercase letter
M is an uppercase letter
m is not an uppercase letter
# is not an uppercase letter
58
Text as Strings
We talked about characters.
How about if we want to represent a sequence of
characters?
cout << "Hello World!" << endl;
"Hello World!"
“COMP2113"
"@_@"
59
C-Strings (Character Arrays)
The low-level internal representation in C/C++ of a string
(i.e., how a string is stored in memory) is an array of char
(i.e., a character array), which is ended by a null character
('\0'). We call this a C-String or a null-terminated string.
The internal representation of the string "Hello World!"
A character array of 13 elements
'H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd' '!' '\0'
• Examples:
char name[16] = { 'J', 'o', 'h', 'n', '\0'};
cout << name;
John
Screen output
You can see that C++ treats the character array name[] as a string
62
C-Strings (Character Arrays)
Or you can simply do the followings to declare a C-
string:
char name[16] = "John"; 1
char name[16];
name[2] = ‘o';
cout << name << endl;
65
The Null character
Recall that the null character '\0' is to indicate end of string.
cout << "Hello " << name << "!" << endl;
Side-notes only: The <cstring> header in C++ provides a set of functions for C-
string manipulation, e.g., string copy strcpy(), string compare strcmp(), string
length strlen(). See http://cplusplus.com/reference/cstring/ for details.
67
Part III
C++ STRINGS
68
What are we going to learn?
• The string class
• String concatenation
• String comparison
• String I/O
• Member functions of the string class for string manipulation, e.g.,
– string::length()
– string::empty()
– string::substr()
– string::find()
– string::rfind()
– …
69
The string Class
• Handling C-string is rather low level, e.g., one will need to deal
with the internal representation (i.e., the character array) and
the null characters.
• C++ standard library provides a class (i.e., programmer defined
data type) named string for more convenient handling of
strings.
• You may think of C++ string as a wrapper/container for
handling char arrays. It provides handy string operations so
basically you don’t need to care about its underlying
representation.
70
String Initialization
• We need to include the header file <string> to use the class
string:
#include <string>
• A string object can be declared using the class name string and
initialized with a C-string or another string object:
71
String Assignment
• The string class has its own end-of-string representation, for
which we do not need to handle.
Screen output
73
String Concatenation
• Two strings can be concatenated to form a longer string using
the binary operator +
I love cats
string msg1 = "I love ";
string msg2 = "cats"; I love dogs
string msg3 = msg1 + msg2;
string msg4 = msg1 + "dogs";
string msg5 = "I hate " + msg2 + " and dogs";
I hate cats and dogs
c1 ?
false c2 ?
true c3 ?
true c4 ?
true c5 ?
true
75
I/O with String Objects
• Both cout and cin support string objects.
• The insertion operator << and extraction operator >> work the
same for string objects as for other basic data types
string msg;
cin >> msg;
cout << msg;
• Note that:
– The extraction operator >> ignores whitespace at the beginning of input
and stops reading when it encounters more whitespaces.
– The word received by a string object will therefore have any leading and
trailing whitespace deleted.
– Cannot read in a line or string that contains one or more blanks
76
I/O with String Objects
Example
Please input a sentence:
#include <iostream> I love dogs
#include <string> Word 1 = "I"
using namespace std; Word 2 = "love"
Word 3 = "dogs"
int main()
{ Screen output
string word1, word2, word3;
cout << "Please input a sentence: " << endl;
How do we read in an entire line including spaces from the input then? 77
Reading a Line from Input
• We use the library function getline() to read in a line from
the standard input and store the line in a string:
string s;
cout << "Please input a sentence: " << endl;
getline(cin, s);
cout << "s = \"" << s << "\"\n";
string_getline.cpp
78
Reading a Line from Input
• The function getline() can be used to read in a line from
the current position until a delimitation character is
encountered
string s;
cout << "Input 2 comma-separated phrases: " << endl;
getline(cin, s, ',');
cout << "1st phrase = \"" << s << "\"\n";
string_getline.cpp
79
Member Functions
• The class string has a number of member functions which
facilitate string manipulation, which includes
– string::length() – returns length of the string
– string::empty() – returns whether the string is empty
– string::substr() – returns a substring
– string::find() – finds the first occurrence of content in the
string
– string::rfind() – finds the last occurrence of content in the
string
– string::insert() – inserts content into the string
– string::erase() – erases characters from the string
– string::replace() – replaces part of the string
More member functions can be found at http://www.cplusplus.com/reference/string/string,
but you are expected to be get familiar with the above functions only for this course. 80
string::length()
• Returns the number of characters in a string object
81
string::empty()
• Returns true if a string object is empty; false otherwise
string s;
if (s.empty())
cout << "s is empty." << endl;
else
cout << "s has " << s.length() << " characters.\n";
s is empty.
What if s = " "?
Is this an empty string? Screen outputs
No, this is a string with a space
character, and its length is 1.
82
string::erase()
• Erase n characters starting at a specific position pos from
the current string
• Note that the string will be modified
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24]
text S t a y h u n g r y , s t a y f o o l i s h
text.erase(11, 6)
Resulting string:
"Stay hungry foolish" pos n
83
Example
string firstName = "Alan";
string name = firstName + " Turing";
string str1 = "It is sunny. ";
string str2 = "";
string str3 = "C++ programming.";
string str4 = firstName + " is taking " + str3;
Screen outputs
84
string::substr()
• Returns a substring of the current string object
starting at the character position pos and having a
length of n characters
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24]
text S t a y h u n g r y , s t a y f o o l i s h
pos n
85
string::substr()
Example
string s; Screen outputs
string str;
It is
cloudy
s = "It is cloudy and warm."; cloudy and warm.
warm.
cout << s.substr(0, 5) << endl; is clo
cout << s.substr(6, 6) << endl; It is cl
cout << s.substr(6, 16) << endl; is cloudy
cout << s.substr(17, 10) << endl;
cout << s.substr(3, 6) << endl;
str = s.substr(0, 8);
cout << str << endl;
str = s.substr(2, 10);
cout << str << endl;
substring.cpp
86
string::find()
• Searches a string object for a given string str, and returns the
position of the first occurrence
find(str)
87
string::find()
This example shows
Example that the search is case-
string s = "Outside it is cloudy and warm."; sensitive
string t = "cloudy";
88
string::rfind()
• Searches the current string object for the content specified
in str, and returns the position of the last occurrence
This is essentially to search in the
rfind(str) reverse direction from the end of
the string
89
string::rfind()
Example
string s = "Outside it is cloudy and warm.";
string t = "cloudy";
90
string::insert()
• Inserts the content specified in str at position pos of
the current string
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]
text S t a y h u n g r y
v e r y
91
string::replace()
• Replaces n characters starting at position pos from
the current string by the content specified in str
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]
text S t a y h u n g r y
f u n n
text.replace(5, 5, "funn")
pos n str
Resulting string: "Stay funny"
92
Example
Screen outputs
93
We are happy to help you!
94