1 Introduction
1.1 Binary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2 From Algorithm to Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2 Variables and Expressions
2.1 Example Programs for the
2.2 Variables . . . . . . . . .
2.3 Expressions . . . . . . . .
2.4 Boolean Algebra . . . . .
Beginner
. . . . . .
. . . . . .
. . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
5
6
9
11
12
15
16
19
3 Conditionals
21
3.1 If, If-Else, If-Elseif-Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.2 Switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4 Loops and Control Flow
29
4.1 For-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.2 While-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.3 For-Loop Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5 Nesting
41
5.1 Conditional Nesting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.2 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
6 Algorithm Design and Analysis
49
6.1 Pseudocode Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
CONTENTS
6.2
CONTENTS
Flowchart Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
52
7 Functions
55
7.1 Function Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
7.2 Function Prototypes, Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
7.3 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
8 Files
8.1 Passing by Reference
8.2 Input from a File . .
8.3 Output to a File . .
8.4 Applications . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
71
72
74
76
78
9 Libraries
85
95
11 Structs
109
12 Recursion
113
A Problem Sets
A.1 Problem Set
A.2 Problem Set
A.3 Problem Set
A.4 Problem Set
.
.
.
.
121
122
125
129
133
.
.
.
.
.
.
.
.
.
.
.
.
.
141
143
144
149
152
159
162
164
167
168
170
175
185
187
B Self-Tests
B.1 Chapter 1 .
B.2 Chapter 2 .
B.3 Chapter 3 .
B.4 Chapter 4 .
B.5 Chapter 5 .
B.6 Chapter 6 .
B.7 Chapter 7 .
B.8 Chapter 11
B.9 Chapter 12
B.10 Pre-Test 2 .
B.11 Test 2 . . .
B.12 Pre-Final .
B.13 Final . . .
1
2
3
4
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
C Notation
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
205
2
CONTENTS
CONTENTS
D Pseudocode
207
E Algorithms
E.1 Computer Science
E.2 Mathematics . . .
E.3 Physics . . . . . .
E.4 Chemistry . . . . .
E.5 Biology . . . . . .
E.6 Philosophy . . . .
E.7 Psychology . . . .
E.8 Linguistics . . . . .
.
.
.
.
.
.
.
.
209
210
213
217
218
219
220
222
224
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
F Flowcharts
F.1 Ball Throw . . . . . . . . . .
F.2 Boolean Switch . . . . . . . .
F.3 Cross Product . . . . . . . . .
F.4 De Morgans Truth Tables . .
F.5 Double Summation . . . . . .
F.6 For Creating Flowcharts . . .
F.7 Ideal Gas Equation . . . . . .
F.8 Ionic Reaction . . . . . . . .
F.9 Manhattan Distance . . . . .
F.10 Transposing a Matrix . . . .
F.11 Dealing a Poker Hand . . . .
F.12 For Writing Pseudocode . . .
F.13 Reversing the Boolean Switch
F.14 Reversing a String . . . . . .
F.15 Summation . . . . . . . . . .
F.16 RNA Transcription . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
CONTENTS
CONTENTS
Chapter 1
Introduction
Contents
1.1
Binary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2
1.1
CHAPTER 1. INTRODUCTION
Binary Operations
n
X
Bi 2 i
(1.1)
i=0
Where i is the ith digit of the binary number, starting from the right-most side. Alternatively, we could
render the n-digit binary number as a vector and take its dot product against a length-n vector of powers
of 2.
To do binary conversion by hand:
For each bit, write down the powers of 2 in increasing order starting with 20 = 1 at the right-most bit.
For every bit which is set to 1, add the corresponding power of 2 to a running sum.
128
1
128
64
0
32
1
+ 32
16
0
+
8
1
+
4
1
+
2
0
+
1
1
+
1 = 173
128
0
64
1
+ 64
32
0
16
1
+ 16
8
0
+
4
0
+
2
1
+
1
0
+
0 = 82
CHAPTER 1. INTRODUCTION
Notice that 101011012 and 010100102 are compliments of each other; that is, each bit of one is the opposite
of the other. Moreover, notice that the sum of their decimal equivalents, 173 + 82 = 255. Why?
The rules for binary addition are simple:
0 + 0 = 0.
1 + 0 = 1.
1 + 1 = 0, carry 1.
To add numbers in binary, add them as you would in a decimal system. Instead of carrying when your sum
exceeds 9 (the highest single digit in decimal), carry when it exceeds 1 (the highest single digit in binary).
10101010
01001001
________
1
10101010
01001001
________
0011
->
->
10101010
01001001
________
1
1
10101010
01001001
________
10011
->
->
10101010
01001001
________
11
1
10101010
01001001
________
110011
->
10101010
01001001
________
011
->
->
10101010
01001001
________
1110011
->
10101010
01001001
________
11110011
111100112 is 24310 . Since 101010102 is 17010 , 010010012 is 7310 , and since 170 + 73 = 243, this is correct.
7
CHAPTER 1. INTRODUCTION
01010101
11011011
________
1111
01010101
11011011
________
0000
11 11111
01010101
11011011
________
00110000
->
->
->
1
01010101
11011011
________
0
11111
01010101
11011011
________
10000
->
->
11
01010101
11011011
________
00
11111
01010101
11011011
________
110000
->
->
111
01010101
11011011
________
000
1 11111
01010101
11011011
________
0110000
->
->
1 111111
01010101
11011011
________
100110000
Since 010101012 = 8510 , 110110112 = 21910 , 1001100002 = 30410 and 85 + 219 = 304, this answer is correct.
8
CHAPTER 1. INTRODUCTION
1.2
Definitions
algorithm
algorithmics
compiler
executable
implementation
interpreter
linker
machine code
object code
pseudocode
source code
CHAPTER 1. INTRODUCTION
10
Chapter 2
Contents
2.1
12
2.2
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15
2.3
Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
16
2.4
Boolean Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
19
11
2.1
Hello, world!
Code 2.1-1: Hello World
1
2
3
4
5
6
7
Line 1 indicates that we will be using the iostream library for input and output. The # indicates a
preprocessor directive; that is, it is an instruction to the code preprocessor to add/switch or modify
code prior to compilation. In particular, #include <iostream> tells the preprocessor that we wish to use
functions and objects from the iostream library. We will use an output stream object, called cout, to
handle output of text to the screen.
Line 2, using namespace std;, is a statement. A statement is an instruction to the compiler to do
something, such as output messages or add numbers. This statement in particular, using namespace std;,
indicates that we will be using functions and or variables from a a namespace called std included from the
iostream library. In particular we will use cout, the object which represents the standard output device.
For the time being, you may take Lines 1-2 for granted.
Line 4 is a function signature, which contains the return type int of the function, the name of the function
main, the arguments and their types (of which there are none here). This is what is called the main
function; all executable C++ programs have them. This particular implementation of main does not have
arguments, but it can. For now, you may also take for granted the fact that every program you write will
have a main function.
Line 5 is another statement. The cout object represents, more or less, the standard output device. The
<< is an operator. In particular it is the output stream operator; its left-hand side indicates the device to
output to, and its right-hand-side gives what will be output. The "Hello, world!\n" is what is known as
a string, or a sequence of characters to be printed out. The \n indicates a newline should be printed after
the exclamation mark. The text is placed in quotes. A semicolon is placed at the end to indicate end-ofstatement. It is important to note that only statements take semicolons at end. Later we will introduce
for-loops and if-constructs, which do not take semicolons.
Line 6 is a return statement. It is a statement to indicate that we are ending the program; moreover, that
a value will be returned from the program. This value serves as a signal to the user or the calling program;
numbers returned from a program can serve as error codes. The keyword return means we will return here,
ending the program. Also, we will return 0, which according to POSIX standards indicates that we have
exited successfully. We would return 1, or some other to POSIX-compliant number, to indicate that we have
exited unsuccessfully.
Line 2 is actually optional. However if we do not use the std namespace, then we must use the scope operator
:: with cout to indicate that we want the particular cout that belongs to the std namespace, as in the
12
Some programmers prefer not to use using namespace at all, and instead refer to functions and objects
from libraries explicitly using the scope operator. This is because some variable, object and function names
from a library might conflict with ones that the programmer uses, as we will later see.
Area of a circle
Code 2.1-3: Area of a Circle
1
2
3
4
5
6
7
8
9
10
11
12
13
The above code illustrates examples of user I/O (input and output).
The above code asks the user for a radius; once the user inputs a number, it returns an area of a circle of
that radius. In the above code, as in most programs we include the iostream library as normal, and use
namespace std to use cout without the scope operator. We also give the signature for main.
However on Line 5, we declare a variable, or name-value pairing, called radius of type float. That is to
say, we want to create a kind of box with a label radius to hold some decimal number which is yet to be
determined. The keyword float indicates that radius is a floating-point number, or number with a decimal.
In general a variable is similar to a box with a label; the name of the variable is the label, and the value is
the contents of the box.
On Line 6 we output to the screen a message that asks the user to input a radius. Line 7 is the actual prompt
for the radius. The cin refers to the standard input device, stdin, or the keyboard. The >> operator is
13
14
2.2
Variables
Introduction to Variables
Abbreviation
bool
*short
*int
*long long
float
double
long double
Long Forms
short int
long int
long long int
Figure 2.1: The * indicates an integer type which may be signed or unsigned (that is, lack a minus sign)
with the unsigned keyword preceding the type upon declaration.
The following code illustrates the use of the most common data types, variable declaration the unsigned
keyword, and def:variable]variable assignment. Lines 5-7 are integer variable declarations. Line 5 declares
a short named seconds. Line 6 declares an unsigned int named height, which means its value cannot be
assigned to a negative number.
Line 8 declares a floating-point number, that is a number with a decimal, called pi, and sets it equal to
the value to the number pi truncated past the 6th decimal place. Likewise on Line 9, a double e has been
initialized to an approximation of Eulers number. Assignment always happens across an = sign. The
assignee is always placed on the left-hand-side, and the value or expression to be assigned always on the
right-hand-side.
Line 10 declares a charthat is, a character literal called day and sets its value equal to the character
literal M. A character literal is any of the numbers, letters, and special characters found on the keyboard;
however in the case of numbers, they are treated as if they were characters (e.g. a serial code 9 as opposed
to the number 9). Character literals are represented as binary or decimal numbers according to the ASCII
code: American Standard Code for Information Interchange. See an ASCII table on-line for conversion.
Lines 11 and 12 assign the previously-declared variables seconds and height to the values -36 and 5 respectively. Since they were previously declared, their data types do not need to be specified upon assignment.
15
seconds ;
height ;
num_particles ;
float
double
char
pi = 3.141592;
e
= 2.718281828;
day = M ;
seconds = -36;
height =
5;
return 0;
}
2.3
Expressions
Operator
+
*
/
%
Operation
Addition
Multiplication
Division
Subtraction
Modulus
Arithmetic Operators
Example
sum = augend + addend;
product = multiplicand * multiplier;
quotient = dividend / divisor;
difference = minuend - subtrahend;
remainder = dividend % divisor
To some extent, you are already familiar with the notion of an operator: *, /, +, - are some arithmetic
operators you have used since elementary school studies. An operator is a symbol that stands for an
operation which to take place among one or more quantities. The arithmetic operators are types of binary
operators, since they require two quantities to make sense. They take a left-hand-side expression and a
right-hand-side expression; we apply the operator left-to-right to produce a result.
All binary expressions have the form left hand side operator right hand side , where operator is one
of *, /, +, -, or %. Expressions can be chained together, as in a = 5 + 3 * 2;. In this case, DMAS order
is followed: division, multiplication, addition, subtraction. Therefore the expression 3 * 2 is computed first
to 6, which is then added to 5 to give 11. Associativity is left-to-right; so a = 2 + 3 - 5 first evaluates 2
+ 3, then takes that result and subtracts 5.
16
Division by integer divisor has an interesting side effect called truncation. For example 5 / 2 does not
evaluate to 2.5 as we might expect; instead it returns 2. This is because 5 and 2 are integers; the result of
any binary operation on two integers returns an integer. Integers (being integers) do not hold the exponent
data required to represent decimals. It can hold the integer portion of the quotient, i.e. 2. In any integer
division that would otherwise result in a number of the form X.Y , the .Y will be truncated, leaving only the
integer X.
Truncation happens even if we declare a variable of type float and store the result in it. However, if
we re-write the expression as 5.0 / 2.0, where the numbers are clearly floating-point, they evaluate to a
floating-point number. In fact, 5.0 / 2 also works, as well as 5 / 2.0. The less-conservative data type is
selected as the type of the expression.
Also beware of division by zero. For example, the following 1.0/0 will give a floating-point error at run-time
since division by zero is impossible.
Typecasting
Typecasting is forcing a value or expression into a type. For example, it is possible to render the integer
5 as type double prior to a division so that the result obtains decimal precision. The syntax for a typecast
is (type ) expression , where type is the data type. expression the value or expression to typecast.
17
Operator
+=
*=
/=
-=
%=
++
--
Operation
Addition
Multiplication
Division
Subtraction
Modulus
Increment
Decrement
Compound Operators
Usage
x += addend;
x *= multiplier;
x /= divisor;
x -= subtrahend;
x %= divisor;
x++;
x--;
Equivalent
x = x + addend;
x = x * multiplier;
x = x / divisor;
x = x - subtrahend;
x = x % divisor;
x = x + 1;
x = x - 1;
A compound operation is an operation that is performed on a variable and written back to that same
variable. An example is x = x + 2. Suppose x was 3 to begin with; then the expression is 3 + 2, which is
evaluates to 5. Thus x + 2 evaluates to 5. However, this result is written back to x because x is assigned to
the value of the expression x + 2. So x then becomes 5, overwriting the old value 3.
Similar examples are x = x - 5, where 5 is subtracted from x and then stored in it; or x = x * 10, and so
forth. Shorthand forms are given in the table above. Two particular shorthand forms are of interest, namely
the increment and decrement operators. The increment operator ++ increases the value of a given variable
by 1, and is the namesake of C++. The decrement operator likewise decreases the value of a variable by
1.
18
2.4
Boolean Algebra
Operator
==
!=
>
>=
<
<=
Operation
equality
inequality
greater than
greater than or equal
less than
less than or equal
Comparison Operators
Example
x == y
x != y
x > y
x >= y
x < y
x <= y
There are six comparison operators. They are depicted in the table above. Example:
cout <<
cout <<
cout <<
(1
== 1);
endl;
(2+2 == 5);
This prints out 1, then 0 to the screen, which represent true and false, respectively. The boolean expression
(1 == 1) tests if 1 is equal to 1. This is true; therefore 1 is printed out. Similarly the boolean expression
(2+2 == 5) tests if 2+2 is equal to 5. It is not, therefore 0 is printed to screen.
The boolean data type accepts these two values, represented as 1 or 0, or true or false, respectively. Boolean
variables can be used in testing boolean conditionals, such as p == p (that is p = p, which is always true).
bool
p;
cin >> p;
cout << (p == p);
The comparison operators are binary operators that perform a test on two expressions, returning two
or false. The resulting formulation is called a boolean expression. For example, the expression 2 == (1
+ 1) is a boolean expression. In this expression, 1 + 1 is evaluated to 2, which is checked for equality for
the left-hand-side 2. These are equal, so the boolean expression returns 1 (true). Likewise (2 + 2) == 5
returns 0 (false). Boolean expressions can be used to test statements whose truth values are unknown.
Operator
!
&&
||
Operation
not
and
or
Boolean Operators
Example
!(x == 1)
(x > 0) && (y < 0)
(x > -2) || (x < 2)
19
Value
0
1
And
0 1
0 0
0 1
20
Or
0 1
0 1
1 1
Chapter 3
Conditionals
Contents
3.1
22
3.2
Switch
27
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
21
3.1
CHAPTER 3. CONDITIONALS
Line 5 sets a boolean value to 1 (true). Then, on Line 6, an if-statement appears. The if-statement always
accepts a boolean value or expression inside of parentheses. Following this, there is a code block encased
by braces. If the boolean value or expression evalues to true, then the code inside of that following block is
executed. If the value or expression is not true, then the code block is not executed; it is skipped instead.
The code block may, in fact, be empty.
If-statements are a class of statements called conditionals, which check for the truth value of some statement
or expression. They are not statements in the sense that, if they contain only boolean expressions, they do
not contain instructional code. In that spirit, they do not contain semicolons to terminate. However, they
may contain calls to functions of type bool.
If-statements are especially useful for executing code in a non-deterministic fashion, based upon user input
or other information that isnt known at compile-time. Examples:
CHAPTER 3. CONDITIONALS
23
CHAPTER 3. CONDITIONALS
Line 5 sets a boolean value to 1 (true). Then, on Line 6, an if-statement appears as normal. A code block
follows, then is terminated by a closing brace. However, following that closing brace is the else keyword.
After the else keyword is a code block. If the boolean expression on Line 6 is true, then the code on Line
7 is executed. However if it is false, then the code on Line 9 is executed. The boolean expression must be
either true or false; therefore one of the two code blocks must be executed. The if-statement and its code
block constitute the if-clause; the else keyword and its code block the else-clause.
Whereas the if-statement applies to one case, the if-else construct is bound to the same conditional. Consider
the code below. There are two if-conditionals; the first checks if rain is set to true; the second checks to
see if it is not set to true. The code below checks the conditionals separately. It would be possible to put
a statement in between the if-conditionals to change the value of the boolean. In an if-else construct, the
else-clause must follow the if-clause; it is not possible to place code intervening the two.
Why would it be desirable to have an if-else construct as opposed to two if statements? This is for efficiency
reasons; in an if-else construct, only one conditional must be evaluated. In two if-statements, two conditionals
must be evaluated. Why would it then be desirable to have two ifs? This is to allow for intervening code that
could potentially change the value of the conditional. For example, after the first if-construct, there could
potentially be a line rain = 0 to set the value of rain to false. Then, upon reaching the second if-construct,
the conditional would then be true and the code inside its block executed.
24
CHAPTER 3. CONDITIONALS
25
CHAPTER 3. CONDITIONALS
In the top code on Line 5, income and factor are declared. The variable factor represents a factor by
which income is multiplied to yield a tax amount. We prompt for income on Lines 6-7, then perform three
separate tests on it to determine factor.
If income is less than or equal to 36900 but greater than 9075, let factor be .15.
In all other cases (that is, when income is greater than 36900), let factor be .25.
Following the tests on Lines 8-16, we print out income*factor, that is the income we were originally given
multiplied by the newly-assigned factor, the value of which is based upon income.
In the top code, three conditionals need to be evaluated. Even if the first conditional is true (that is if an
income of less than 9075 is entered) and factor is assigned a value, the two conditionals afterward are still
evaluated (to false). As a result, factor does not change from its initial assignment of .1. This additional
testing is an unfortunate waste of clock time, since we assigned factor already.
To improve this situation, we introduce the if-elseif-else construct. This allows us to chain together mutually
exclusive if-statements. A set of conditionals is mutually exclusive if only one of the conditionals in the
set may be true. If-elseif-else constructs are useful for when the code inside it should be executed in a
mutually-exclusive fashion, for example, assigning a letter grade based upon a score.
The bottom code achieves the equivalent result of the top code and on average, tests fewer conditionals. If
income < 9075 is evaluated to true, the code block within is executed and the total construct is exited;
no others need to be tested because the conditionals are mutually exclusive. If income < 9075 is false,
then income <= 36900 is tested. This case actually covers income > 9075 && income >= 36900; if the
processor arrives at the conditional income <= 36900, the construct was not exited, which must mean
that income < 9075 was false, which in turn means that it is already known at this point that income >=
9075.
Likewise the else-clause tests income > 36900, based upon the fact that neither of the previous conditionals
could have been true if the program arrived at the else. The variable factor is guaranteed to be assigned
a value, since by the mutually-exclusive nature of if-elseif-else, all possible conditional cases are covered.
26
CHAPTER 3. CONDITIONALS
3.2
3.2. SWITCH
Switch
The switch construct is used for testing multiple cases of a variable. It can be used as a more concise
substitute for if-elseif-else when testing equality of a variable against several known possibilities. For example,
in the above code, a letter grade is solicited and placed into the grade variable (a character, which is expected
to be A, B, C, D, or F). Line 9 begins the construct with the keyword switch and the variable for
which to test cases inside the parentheses, in this case grade. Within the body of the switch are the cases.
For each case, the case keyword is given followed by a possible value of the variable, then a colon. If the
variable grade equals the value given after case, the indented code block is executed.
Inside of each code block, a variable baseline is assigned to a value corresponding to grade. Following this,
for each code block the break keyword ends the code block. The break keyword transfers control outside
the switch construct.
A default case may be given to handle all cases not elsewhere covered in the switch construct. If the variable
27
3.2. SWITCH
CHAPTER 3. CONDITIONALS
does not equal any of the given values covered by other cases, the default case block will be executed.
28
Chapter 4
Contents
4.1
For-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
30
4.2
While-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
31
4.3
For-Loop Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
32
29
4.1. FOR-LOOPS
4.1
For-Loops
The above code introduces a loop, a form of control flow structure for directing the flow of program
control. This loop is a type of for-loop, a form of loop whose repitition is controlled by three statements:
The initialization phase sets a variable, i=1, to indicate the initial state of the loop. The conditional,
i<=n, indicates the loop will continue as long as i<=n is true. The increment statement, i++, advances i.
This loop will begin with i=1, then for each iteration or advancement of the loop, it will output i. For each
iteration, i will increment by 1 (that is, 1 will be added to i) and the statement on Line 8 will be executed,
thus printing the value of i to the screen. If 5 is entered,
1 2 3 4 5
will be printed. Note that, as with all control structures, a one-line body may omit braces; multi-line bodies
(except nested structures) require them.
The applications of for-loops in combination with what we have covered so far are broad. By manipulating the
initialization, conditional, and increment statements as well as the body of the loop, we can perform sums and
products, numerically evaluate functions, and even find their difference and finite integral approximations.
Later the double-for will be introduced; it covers a wider array of applications, including double-summations
and difference and integral approximations of higher-order functions.
30
4.2
4.2. WHILE-LOOPS
While-Loops
The above code demonstrates the use of a while loop. In a while loop, the code inside the body is executed
so long as the condition following the while keyword is true. On Line 5 i is set to 0, which satisfies i < 10,
so the while-loop is entered. For each iteration, it prints out i, then increments it. When i is incremented
to 10, the while loop checks the condition againit is now false, so the loop exits.
The code below demonstrates the use of a do-while loop. It is similar to a while loop, except the loop
is entered and one iteration is completed no matter what; the while conditional is evaluated at the end of
each iteration of the loop instead of at the beginning. Note that a semicolon (;) is required at the end of a
do-while construct.
It is generally inadvisable to use while-loops for deterministic looping; for-loops are better for that purpose
instead. While-loops are best used where the loop should be broken out of upon some known eventuality.
A while loop whose conditional never becomes false is an infinite loop. Interestingly, it is impossible for a
machine to tell if a program is running infinitely or not (known as the halting problem), so if you create an
infinite loop, you will need to terminate the program yourself (Ctrl+c).
31
4.3
For-Loop Applications
The above code prints out a sequence; that is < a1 , a2 , a3 . . . ai . . . a10 > as defined by the formula ai = i2 .
Note the use of integers and a step size of 1. The code below prints values of a continuous function x2 from
0 up to 1 in steps of .01, resulting in 100 values. Line 9 controls x to range from 0 to 1, incrementing by .01
each iteration. On Line 10 the function x2 is computed and assigned to f. Lines 12-13 print both x and the
function value, separated by a : . Additionally, the setw and setprecision functions are called to set the
number of spaces alloted to right-aligned output and precision (number of digits past the decimal). Each
time a variable is output with cout in this way, setw and setprecision will need to be re-defined for the
next output if they are used.
Line 11 contains the typecast expression (int)(x*100)%5; first x*100 is computed to a whole number, then
typecast to an integer; finally we modulus the product by 5, giving a number in the range of 0 to 4. If the
product is divisible by 5, the modulus is 0; thus every 5th step, we expect the equality to be true and an
additional new line is printed.
32
33
Consider the sum of numbers 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55. The sum of the numbers 1 to 10,
and in general the sum of numbers 1 to n may be represented as:
10
X
and
i=0
n
X
i.
i=0
The above program performs summation from 1 to a given n. It declares a counter i and n as well as an
accumulator S which is initialized to 0 (this is because all sums implicitly start with 0). It then prompts
the user for a number n. On Line 8 it then checks to see if n is a candidate for summing up to from 1 (it
must not be less than 1). If it is not a proper candidate, the error code 1 is returned to indicate an error.
If n >= 1 we proceed. Line 9 demonstrates a for-loop which starts at 1, increments by 1, and ends at n.
For each iteration, S accumulates i. Finally when i == n, the program breaks out of the loop. S holds the
resulting sum.
When performing sums and products, it is important to initialize the accumulator to the correct value. In
the case of sums, this is usually a 0, since all sums implicitly begin at 0. E.g. if we add 1+2+3 to a running
sum, we begin with 0, add 1 to it so that 0+1=1; then to 1 add 2 so that 1+2=3; then to 3 add 3 so 3+3=6.
In the case of products, we typically begin with 1 rather than 0; this is so the product begins with the first
multiplicand. Beginning a product with 0 sets the total product to 0.
34
Consider the product 1 2 . . . 10 = 3628800. The product of the numbers 1 to 10, and in general the
product of numbers 1 to n may be represented as:
10
Y
and
n
Y
i.
i=1
i=1
The above code will deconstruct a given product, successively dividing out numbers from the product until
it is reduced to 1, to find the number n that gave rise to the product. The pivotal part of the program
is in the conditional statement of the for-loop: the program breaks out of the loop when P becomes 1. P
becoming 1 means we hit the last number, n; thus after the loop ends, i will contain 1 plus n.
35
The above code illustrates the use of the double for-loop, a type of nested loopthat is, a loop inside of
loop. The above double for-loop prints a multiplication table. The j for-loop is called the outer loop and
the i for-loop the inner loop. For a variable j which ranges from 1 to 10, a total inner loop is executed.
At the beginning of the execution of the inner loop, the value i is reset to 1. In that inner loop, a variable
i ranges from 1 to 10; for each iteration, the product of i and j is printed out. After the inner loop finishes
executing, the line is broken, and the outer loop resumes with a re-iteration.
The code below demonstrates prints the double-summation (1) + (1 + 2) + (1 + 2 + 3) + . . . (. . . + 10), or
j
10 X
X
i,
generally
j=1 i=1
j
m X
X
i.
j=1 i=1
For each iteration of the outer loop, the total inner loop executes. The inner sum over i from 1 to j occurs for
each j as j ranges from 1 to 10. The inner loop thus accumulates all of the inner sums 1, 1 + 2, 1 + 2 + 3, . . ..
After the outer loop exits, the variable sum holds the final result of the double-summation.
36
The above while loop considers the death of the damping function
f (x) = ex sin(x),
a sine wave, defined on Line 13. A running average of the absolute value of the function is computed every
iteration inside a while loop. So long as the loop runs, x and f are printed to stdout. When the running
average is less than .1, the loop stops and reports the value of x. Effectively, this prints the lively part of
the function, exiting only once the running average has reached the value .1.
37
The above code produces a numerical approximation, the forward or left difference approximation to the
derivative of x3 = 3x2 over the range [-2, 2] in step sizes of .1. The range is established on Line 9; on Line
10 the function is computed and stored into f2. On Line 11 the difference d is computed as f2 f1 ; this is
a difference in values of the function f (x) = x3 over very small intervals of x (.1). On Line 12 we put the
value of f2 into f1 to serve as the old value for the next iteration. Since we required f1 on Line 11, we
had to have computed a suitable initial value for it, 1.93 . Finally on Lines 13-14 we print the result out,
remembering to divide the difference d by the width, .1.
The code below exemplifies the trapezoid rule for approximating the integral
#
"
Z 2
n1
X
h
3
fi + fn .
x
using
f0 + 2
2
1
i=1
Code 4.3-12: Trapezoid Rule
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
38
39
40
Chapter 5
Nesting
Contents
5.1
Conditional Nesting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
42
5.2
Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
44
41
5.1
CHAPTER 5. NESTING
Conditional Nesting
The above code accepts whitespace-delimited booleans a and b. If a is true, the value of b is flipped (1
becomes 0; 0 becomes 1). If a is false, nothing happens. Then the values are output space-delimited. In
this example, the if-else construct is nested inside the if construct. Total constructs can be placed inside,
or nested inside other constructs. If only one construct is nested, and there are no other statements
inside the parent construct, the parent construct does not require braces; however if there are two or more
statements/constructs, braces are required.
The code below accepts a boolean a. If a is true, it prints the odd numbers; if a is false, it prints the even
numbers.
42
CHAPTER 5. NESTING
The code above accepts a boolean a. If a is true, it runs a loop which prints the odd numbers to 10 by
starting at 1 and incrementing 2; if a is false, it runs a loop which prints the even numbers to 10 by starting
at 0 and incrementing by 2.
The code below accepts a boolean a. Then it runs a loop in which a conditional is evaluated every iteration.
If i%2 is equal to the a put in, the number is output. If a is 0, this conditional is true for even numbers; if
a is 1, it is true for odd numbers. That is, a holds the parity of the sequence.
43
5.2. APPLICATIONS
5.2
CHAPTER 5. NESTING
Applications
The above code accepts an integer input n, then factors it. It ranges up to n; if any number between 1 and
n inclusive passes a modulus test for even ni divisibility, it is output.
Algorithm Factor(n):
44
CHAPTER 5. NESTING
5.2. APPLICATIONS
Above is a quadruple for-loop which washes all possible binary combinations abcd through a series of
boolean conditionals to produce a four-digit binary output code. The variables are declared as integers to
allow for looping; each begins at 0 and ends at 1 with 1 step.
From the exhaustive output, it is plain to see what input values gave rise to the given outputs. This is one
way to obtain information about function inputs given their outputs; plug possible inputs into the function
until the output is obtained.
45
5.2. APPLICATIONS
CHAPTER 5. NESTING
This code utilizes the cstdlib library for the rand() function and time.h library for time(). First the
user is prompted for N , a number of trials to perform. Once entered, the program for N iterations rolls
a pair of six-sided dice and sums their values. If the sum is 7 or 11, it increments a running tally into j.
Once finished, it typecasts the integer division Nj and prints to stdout, yielding the estimated probability of
rolling a 7 or 11.
Line 10 seeds a psueorandom-number generator. To seed an psuedo-RNG is to provide an initial value
to it so that it may generate a sequence of pseudorandom numbers. If the user wishes for the sequence to
change over time, the current time is a good seed. Current time can be gotten from the function time(),
which accepts NULL. On Line 12, integer a is initialized to a random value between 1 and 6 with rand()%6+1.
The function rand() has a high default max value which can be controlled using modulus.
Algorithm p-Estimate(n):
1. Let j = 0;
2. For n trials:
(a) Generate random dice roll (a, b) : 1 a 6, 1 b 6.
(b) If a + b equals either 7 or 11, increment j.
3. Output
j
.
n
46
CHAPTER 5. NESTING
5.2. APPLICATIONS
The above code finds prime numbers from 2 up to 100. It works by examining eachnumber jin the range as
a candidate for inclusion into the set of primes. It looks at all numbers i less than j. Why j instead of j?
This is because each product is composed of a multiplicand and multiplier; Either the multiplier is greater
than the multiplicand, or vice versa; or else they
are equal. If they are equal
the number is not prime, so we
need not check it. All potential multiplicands < j have multipliers > j, and by
the associative property
of multiplication, this relationship is symmetric. Thus we only need to check up to j for one multiplicand.
Each number j is innocent until proven guilty: until a number is found that can divide out evenly, we
keep looking. If anywhere in the loop there is found an i which divides evenly into j, the boolean prime or
p is marked false. If after the loop p is true, j survived the search, so we output it as prime.
Algorithm Find-Primes():
j:
47
5.2. APPLICATIONS
CHAPTER 5. NESTING
Algorithm Heatup():
48
t
2
as an integer.
Chapter 6
Contents
6.1
Pseudocode Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
50
6.2
Flowchart Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
52
49
6.1
Pseudocode Design
1. Based upon P , identify I, the set of inputs, their types, and their descriptions. Write these down.
2. Identify the desired output O. This is what is output or returned by the algorithm. Write this
down as well.
3. Now solve an example case P 0 by hand; but in doing so, for each step ai in the process of solving
P 0:
(a) If ai is done in sequence, or many times, encase step ai within an iterative structure (a for,
while, or do-while loop). Identify the parameters of the structure so that the repeated step
ai is executed with correct starting conditions, stopping conditions, and step.
(b) If ai is done conditionally, encase it within a selection structure (if, if-else, if-elseif-else, or
switch). Identify the conditions required to make ai execute only when it should.
(c) Write down the step ai , without regard to its order in the final algorithm A.
Use the problem specification P to identify the steps that need to be taken, in order from the most
obvious to the least. Bear in mind that the objective of the final algorithm A is to obtain O given
I.
4. Then re-order all ai you have identified so that P is solved (O is obtained from I).
5. Until A can be used to solve P 0 :
(a) Check A by solving the example problem P 0 by following all the steps in A, in order.
(b) Insert, remove or modify steps in A to account for missteps.
6. Return A.
50
Read P critially.
Scan for relevant
information.
Start
true
Example
problem
solved?
false
Pseudocode
can solve
example?
false
true
First time
solving the
problem?
true
false
Re-order, modify,
insert, or delete
steps until the
problem is solved.
51
Finish
6.2
Flowchart Design
1. Based upon P , identify I, the set of inputs, their types, and their descriptions. Write these down
and draw parallelograms around them.
2. Identify the desired output O. This is what is output or returned by the algorithm. Write this
down and draw a parallelogram around it if it is output, or bubble if it is returned.
3. Now solve an example case P 0 by hand; but in doing so, for each step ai in the process of solving
P 0:
(a) Write down the step ai , without regard to its order in the final algorithm A.
Use the problem specification P to identify the steps that need to be taken, in order from the most
obvious to the least. Bear in mind that the objective of the final algorithm A is to obtain O given
I.
4. For all the steps you have written, draw arrows as follows:
(a) If ai is done in sequence with similar steps, or many times, encase the step within an iterative
structure (a for, while, or do-while loop) by drawing arrows in a loop which contains ai .
Identify the parameters of the structure so that the repeated step ai is executed with correct
starting conditions, stopping conditions, and step.
(b) If ai is done conditionally, identify the conditions required to make ai execute only when it
should, then write those down. Encase ai within a selection structure (if, if-else, if-elseif-else,
or switch) by drawing a diamond around the condition, then branching to ai only if the
condition is true.
5. Then order all the other ai you have identified by drawing arrows indicating the flow of the steps,
so that P is solved (O is obtained from I).
6. Until A can be used to solve P 0 :
(a) Check A by solving the example problem P 0 by following all the steps in A, in order.
(b) Insert, remove or modify steps in A, or re-draw arrows, to account for missteps.
7. Return A.
52
Read P critially.
Scan for relevant
information.
Start
true
Example
problem
solved?
false
Flowchart
can solve
example?
false
true
First time
solving the
problem?
true
false
Delete or insert
steps, re-draw
arrows to try to
solve example
53
Finish
54
Chapter 7
Functions
Contents
7.1
Function Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
56
7.2
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
59
7.3
Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
63
55
CHAPTER 7. FUNCTIONS
7.1
Function Basics
The above code demonstrates the use of a function, or module of code which defines an input-output
relationship. The input consists of arguments to the function, and the output is the return value.
In this example, the function is f of return type int, which accepts x, also of type int, as its argument. This
is to say that f is a function which accepts an integer and returns and integer as output. The function f
returns x*x, which is simply x2 . Thus, when we run integer x values in the range [5, 5] through it, we
expect back values of x2 for integer values of x in that range.
56
CHAPTER 7. FUNCTIONS
The code below demonstrates the use of multiple arguments in a function call. The inputs given in the
function call are called arguments, while the variables in the function signature for f are called parameters.
The values 2, 3, and 5 are put in order as the arguments to f; thus they are assigned in that order to the
parameters in the function signature for f. Thun x1 holds the value 2, x2 holds the value 3, and x3 holds
the value 5. Finally the function prints the values.
57
CHAPTER 7. FUNCTIONS
The above code defines a function hello of type voida type with no return value. The function hello
takes no arguments, and has only one statement, which outputs Hello, world! with linebreak to stdout.
The function main calls hello, thus executing the code within.
The code below calls the function hello ten times inside of a loop, giving the iteration number aligned to
the left.
58
CHAPTER 7. FUNCTIONS
7.2
The above code demonstrates the use of prototypes. When the call hierarchy of the functions in a C++
source file are out of orderthat is, if they are called before they are definedthen any functions called
before their definitions require a prototype. A prototype is a function signature; it gives the name of
the function, followed by a list of the functions arguments and their types. Finally it is terminated by a
semicolon. Prototypes are typically placed at the top of the source file after the preprocessor directives.
It is noteworthy that the parameter names in a function prototype do not have to match the parameter
names in the function definition, although they must have the same types.
59
CHAPTER 7. FUNCTIONS
As in mathematics, functions calls can have composition relationships. A function A may be called on a
value; then a function B may be called on the value returned by A; then a function C may be called on the
value returned by B; and so forth.
In the above example, half the square of (n+1) may be found by defining functions halve, increment, and
square. First, n (or 3 in the code) is incremented by 1 to return 4, which is then squared to produce 16,
finally halved to produce 8. The program control flow always works from the innermost function call to the
outermost.
60
CHAPTER 7. FUNCTIONS
This code illustrates call hierarchy, or the order in which functions call each other. In the example, c calls
b which calls a.
61
CHAPTER 7. FUNCTIONS
c );
int main () {
cout << add (1 ,2) << endl ;
cout << add (
( float )(1.0) ,
( float )(2.0)
)
<< endl ;
cout << add (1 ,2 ,3) << endl ;
}
int add ( int a , int b ) {
cout << " Integer add : " ;
return a + b ;
}
float add ( float a , float b ) {
cout << " Floating - point add : " ;
return a + b ;
}
int add ( int a , int b , int c ) {
cout << " Three - integer add : " ;
return a + b + c ;
}
The above code gives two implementations of a function add which adds two integers a and b. One function
accepts arguments of type int and returns int; another accepts arguments of type float and returns float;
yet another accepts three ints. When the function is called, the appropriate function is executed depending
on the arguments. This is overloading, or multiply-defining the function for a different argument set and
return type; and is done to provide greater flexibility when calling functions.
62
CHAPTER 7. FUNCTIONS
7.3
Applications
The above code defines functions sum and prod. Algorithm Sum is given below in pseudocode.
Where
b
X
i = S,
i : i%j = 0,
i=a
1. Let S=0.
63
CHAPTER 7. FUNCTIONS
64
CHAPTER 7. FUNCTIONS
The above code prints a multiplication table for all numbers x in the range [x1 , x2 ] by all numbers y in the
range [y1 , y2 ]. First a column header of y values is printed, followed by a delimiter and then the table. Prior
to the first entry in each row of the table, the x value for that row is printed followed by a delimiter. Then,
the inner for-loop generates the xy values printed.
65
CHAPTER 7. FUNCTIONS
The above code gives a function definition for f (x) = x2 5x + 6, then uses a left difference approximation
to find an approximation of the derivative f 0 (x) for any x, defined by the formula:
f 0 (x) =
f (x) f (x h)
,
h
where h = .01.
An alternative way to write the above code would be to define
f1 = f (x h) = (x h)2 + 5(x h) + 6
then compute
f f1
.
h
66
CHAPTER 7. FUNCTIONS
67
CHAPTER 7. FUNCTIONS
This code illustrates a re-encoding of a 2-bit sequence ab. If a is true, b is flipped; then b is evaluated. If it
is true, then the value of a is flipped. So
00 yields 00;
01 yields 11;
10 yields 01;
11 yields 10.
68
CHAPTER 7. FUNCTIONS
}
return f ;
}
int main () {
cout << fib (5) << endl ;
}
The Fibonacci sequence is the sequence h1, 1, 2, 3, 5, 8, 13, 21, . . .i. It is defined recursively as:
f1 = f2 = 1.
fi = fi1 + fi2 , i : i > 2.
However in this example, it is generated dynamically using a for-loop. The argument i refers to the ith
Fibonacci number, thus the loop works up to i. Each iteration, f is reset to f1 + f2 . Then f1 inherits the
value of f2 , and f2 inherits f the values shift down for the next iteration.
i
1
2
3
4
5
f1
1
1
2
3
5
f2
1
2
3
5
8
69
f
2
3
5
8
13
CHAPTER 7. FUNCTIONS
70
Chapter 8
Files
Contents
8.1
Passing by Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
72
8.2
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
74
8.3
Output to a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
76
8.4
Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
78
71
CHAPTER 8. FILES
8.1
Passing by Reference
word [4]);
word [5]);
word [8]);
word [7]);
word [8]);
72
CHAPTER 8. FILES
Where
a
b
:
:
int
int
: int to swap
: int to swap
1. Let c a.
2. Let a b.
3. Let b c.
4. Return (a, b).
73
CHAPTER 8. FILES
8.2
>> sylls )
{
<< setw (4) << sylls ;
<< setw (10) << word << endl ;
This example demonstrates a file read. The read is done on words.txt, which contains two fields: the first
is a word, and the second an integer denoting the number of syllables the corresponding word contains. The
above program will read in the word and number of syllables, and output them to standard output in reverse.
The ifstream class from the fstream, or file stream, library is used to represent an input stream from a
file, similar to the input stream stdin. An object infile is declared on Line 10 to be used as the file input
stream object.
Line 11 uses the function open on the infile object to open a file words.txt. This is a type of class method, or
function which is associated with an particular object. When using C++ class methods, one always precedes
the function call with the name of the object and a dot (.). The open method accepts a string, which is the
name of file to be opened. After an open is done, the file input stream object infile should be checked to
see if the file open was done successfully. This can be done simply with if on infile.
In the case that the file is opened and can be read from, the data from each line in the file will be read into
word and sylls (in that order) via use of the input stream operator (>>). Similar to cin, infile serves as
an input stream to input data. The entries in the file may be space or tab-delimited. As long as there is
data to read from the file, it will read it, and execute the code inside the while-block.
Inside the while-block the syllable is printed first, then the word. The left refers to std::left, a left-flush
74
CHAPTER 8. FILES
operator. Similarly there exists std::right for right-flushing. On the condition that the file open fails (file
not found, wrong permissions, etc.), an error message is printed to that effect.
75
CHAPTER 8. FILES
8.3
Output to a File
This code demonstrates outputting data to file. It prints the ASCII (American Standard Code for Information Interchange) table from 33 to 126 inclusive. This includes all alphanumeric and special characters,
but not tabs, backspaces, newlines, and so forth.
For handling file output, we declare an object of class ofstream, or output file stream, called outfile. This
outfile serves as the output file handling object. Similarly to reading, we call open on it. If the open is
successful, a for-loop runs from i in range [33, 126] and outputs the left-flushed counter and right-flushed
character corresponding to that ASCII integer encoding.
By default, a file is truncated when it is opened for writing in this fashion.
76
CHAPTER 8. FILES
77
CHAPTER 8. FILES
8.4
8.4.1
Applications
Ionic Data Lookup
name
symbol
charge ) {
name )
return symbol ;
}
}
cout << << n << " was not found . " << endl ;
exit (1);
}
int main () {
string ion ;
cout << " Enter the ion name : " ;
cin >> ion ;
cout << " The corresponding symbol is " << symbol ( ion );
cout << " . " << endl ;
return 0;
}
The above code prompts for a string ion which should contain the name of an ion. It then looks up the
symbol of that ion via a function symbol.
The function symbol reads entries from a file ions.dat containing an name, symbol, and charge. If the
string that was passed to symbol matches the name in any given entry, the symbol is returned. The return
statement will exit the function. If the whole file is read and no symbol is found, a message is printed at
end to that effect, and the function exit from <cstdlib> is called with error code 1 (equivalent to main
returning 1) to indicate an error.
78
CHAPTER 8. FILES
8.4.2
Self-Copying Programs
This program is an example of advanced file I/O concepts, including binary reading, binary writing, and
system command execution on files.
The program is compiled and run as follows:
The executable a.bin will then have its instruction code copied to memory as it executes. It will open
itself for binary reading (Line 11), then increment the first letter in its name (argv[0], whose first letter is
argv[0][0]) so that a becomes b (Line 12). It will then open a file by that name called b.bin (Line 13) for
binary writing.
It then allocates a character pointer called c for a character array of size 1 to prepare to copy itself
79
CHAPTER 8. FILES
byte-wise. Pointers will be discussed later; for now, let it suffice to say that c acts as a handler for a single
character. The file is then copied byte-wise (Lines 15-16) and both files are promptly closed (Lines 17-18).
The program then prepares a character buffer of size 16 (Lines 20-21) to hold a command to execute, that
is chmod 755 (Line 22). It appends the name of the new files to make chmod 755 b.bin (Line 23), which
renders the new file executable once executed (Line 24). Finally the new file is executed as in b.bin (Line
25).
80
CHAPTER 8. FILES
8.4.3
Forensics
This file is an application of advanced file I/O concepts such as block reading and binary file processing.
The aim of this program is to recover ASCII blocks whose size are at least N from a 5 14 floppy disc whose
contents were recovered into a file called floppy.dat.
The program opens the file in binary mode (Line 17), then initializes a pointer to a one-byte character array
for byte-wise reading. A size-N character array is declared (Line 19), and a counter initialized (Line 20). So
long as the floppy can be read from (Line 21), if the character we are reading is an ASCII character (Line
22) and the block buffer is not yet filled, we read it into the block buffer (Line 23). But if the block buffer is
full we output the block (Line 24) and continue to output the ASCII (Line 25). If we encounter a non-ASCII
81
CHAPTER 8. FILES
character (Line 26) and we had already read a block, we print a newline (Line 27), and regardless we reset
the counter back to 0 to indicate that we wish to start a new block.
Once the program finishes reading, it close the file (Line 31).
82
CHAPTER 8. FILES
8.4.4
This program will parse notes inside a data file notes.dat to obtain the number of half-steps that a note is
from A4. The file is notes.dat, which contains the following strings:
Ab4
A#4
B3
Each string contains a note (A, B, C, D, E, F, G), a flat/sharp indicator (b or #), and a number indicating the
octave. So Ab4 indicates A[4 .
83
CHAPTER 8. FILES
A[4 is -1 half-steps from A4 while A#4 is 1 half-step from A4 . B4 is 2 half-steps from A4 , while G3 is -2
half-steps from A4 . A difference in note (A, B, C, etc.) indicates a separation of 2 half-steps; a flat-sharp is
1 half-step; and an octave is 12: 2 for each of the seven notes, except there is no half-step between B and C
or E and F .
The program reads the strings indicating the notes into note and calls a function half steps of return
type int to calculate the half-steps. In that function, first character in the string note, which gives the
music note, is subtracted off from the literal character 0, whose ASCII decimal equivalent is 65. Also, the
equivalent of A is 65, B is 66, and so on. Thus the difference note[0] from A is equivalent to the number
of steps away. Multiplying by 2 gives the number of half-steps (since two half-steps form one step).
To deal with the optional flat/sharp indicator, we introduce i as a variable index. If in fact note[1] is a flat
or sharp indicator, we decrement or increment n; also we increment i in either case so that i then equals 2,
and thus indexes the octave. If note[1] is neither a flat nor sharp indicator, we do no such increment and
i still then references the octave number (since it must be at position 1).
The half-steps per octave is 12 (for 7 notes per octave, 2 half-steps per step, with two exceptions), and we
subtract note[i] from literal 4 to obtain how many octaves removed from A4 we are.
84
Chapter 9
Libraries
85
CHAPTER 9. LIBRARIES
<<
<<
<<
<<
cout
cout
cout
cout
<<
<<
<<
<<
// Arc
cout
cout
cout
cout
<<
<<
<<
<<
// Hyperbolic
cout
cout
cout
cout
<<
<<
<<
<<
log ( x )
<< endl ;
log2 ( x ) << endl ;
log10 ( x ) << endl ;
endl ;
// Natural log
// Base 2 log
// Base 10 log
cout
cout
cout
cout
<<
<<
<<
<<
// x ^ y
// Square root
// e ^( x )
// Round number up
// Round down
// Round off
// Absolute value
<< endl ;
return 0;
}
This code demonstrates use of the math functions. Note that trigonometric functions accept and return
radians. Of the math functions, it is important to know the following: sin, cos, tan, asin, acos, atan, exp,
pow, log, sqrt, abs, ceil, floor, and round.
86
CHAPTER 9. LIBRARIES
This code will blink two strings a and b back and forth on the screen for durations t1 and t2 , respectively.
The pseudocode on the following page describes the code.
Line 26 introduces a new data type, string. A string is data type for holding sequences of ASCII characters.
Later we will see how to manipulate string contents.
See the algorithm for details.
87
CHAPTER 9. LIBRARIES
This program types out Hello, world! to the screen. First it declares a variable of data type string,
then calls the typeout function defined above. The typeout method accepts a string str as a parameter,
declares counter i and unsigned int naptime, the number of microseconds (sec) to wait between printing
characters. This is set to 30 ms.
For the total length of the string, typeout will output each character, flushing the stdout buffer from
memory onto stdout with each character print, wait for 30 ms, then repeat.
Where s is the string to type out, and d is the duration (unsigned int) to wait,
define Algorithm Typeout(s, d):
1. Let S size(s).
2. For each i in the range [0, S):
(a) Print s[i].
(b) Wait for duration d.
88
CHAPTER 9. LIBRARIES
Above are two functions x intercept and quadratic, defined in a file algebra.cpp. The corresponding
function prototypes are defined inside algebra.h, which is included in this function definition file.
The functions are defined inside their own namespace, alg. Similar to the cout object and its std namespace,
in order to refer to the functions outside of the alg namespace, one must use the scope operator (::) as in
alg::quadratic(a, b, c); that is, unless the statement using namespace alg; appears where they are
to be used.
89
CHAPTER 9. LIBRARIES
Above are the contents of the function definition file algebra.h. Within are function prototypes for
x intercept and quadratic, defined in a separate file algebra.cpp. This is the header file that must
be included by algebra.cpp and all examples which use the library.
The prototypes in the header files are defined inside their own namespace, alg; the significance of namespace
is explained along with algebra.cpp.
This file, main.cpp, tests libalgebra. The algebra.h header file must be included to use the functions
x intercept and quadratic. Also, using namespace alg; is included to call the functions without explicitly giving their scope (::).
90
CHAPTER 9. LIBRARIES
91
CHAPTER 9. LIBRARIES
92
CHAPTER 9. LIBRARIES
str );
str , unsigned int naptime );
int b , int step );
int b , int step , unsigned int naptime );
This example file demonstrates the use of the overloaded function void typeout(int a, int b, int s)
in libtypeout. It is called inside of a loop which ranges from [1, 100]. For each iteration of the loop, a
sequence up to i is typed out; thus 100 sequences of i from 1 to 100 inclusive are typed out.
93
CHAPTER 9. LIBRARIES
94
Chapter 10
95
The above code illustrates the use of an array, or ordered collection of values. Arrays stand in contrast
to scalars, or single-value variables. Arrays are indispensible for tasks which require that data remain in
memory. For example, the reversal of a user-supplied string requires that we keep track of the values in the
string as we perform the reversal.
The above code initializes an array a to values in the range [1, 10], then squares them, writes them back to
the array, and prints them to stdout. Line 7 gives the syntax for initializing an array. Here, a is the variable
name. Upon initialization, the size of the array is provided in square brackets. In this program, the size is
defined as a macro on Line 4 (N = 10).
Array indexing begins at 0. So we may refer to the first element a1 in the array as a[0], the second element
a2 as a[1], the nth element an as a[N-1]. In general, indexing in mathematical notation begins at 1; however
in these notes, the C++ indexing scheme will be honored.
Line 10 begins a for-loop which ranges i over [0, N ). N is not included in the range since array indexing
begins at 0; the range [0, N ) thus covers all N values. The value a[N ] actually holds what is called the null
terminator, or \0, which indicates the end of the array.
Line 11 performs the squaring computation and sets the value back to the array. An alternative syntax is
a[i] *= a[i]. Line 12 prints the ith value ai .
Line 9 is a commented statement that would change a[7], which is the value 8, to 6. This statement
illustrates assignment of array elements. Try uncommenting Line 9 to see how the output changes as a
result.
96
~u ~v =
n
X
ui vi
i=1
Line 13 defines size n = 5, and arrays u and v on Lines 14-15. Then the return value of dot is printed.
The function dot accepts two vectors u and v and a size n; then simply sums the product of these two arrays
over i.
97
3 , 10 , 1 , 7 ,
" << setw (2)
" << setw (2)
" << setw (2)
" << setw (2)
98
2 , 4 , 9 , 6};
<<
min ( v )
<< argmin ( v )
<<
max ( v )
<< argmax ( v )
<<
<<
<<
<<
endl ;
endl ;
endl ;
endl ;
Where
~a
1. Let min v0 .
2. For i in the range [0, n):
(a) If min > vi :
i. Let min vi .
3. Return min.
Where
~a
argmin
1. Let min v0 .
2. For i in the range [0, n):
(a) If min > vi :
i. Let min vi .
ii. Let argmin i.
3. Return argmin.
99
<< endl ;
The above code illustrates a summation over an array. With some minimal editing, functions for the product
and average of an array can be obtained. For product, we change the + to a *; for finding the average, we
return sum/N.
Likewise, functions for the sum of squares and standard deviation can be defined. With the creation of
additional arrays, mode and median can be defined, even for unsorted arrays.
100
2,
5,
3,
1,
4,
2,
5,
2,
3,
1,
4,
5,
5} ,
4} ,
1} ,
3}
};
int i , j ;
for ( i =0; i < N ; i ++) {
for ( j =0; j < M ; j ++)
cout << A [ i ][ j ] << " " ;
cout << endl ;
}
return 0;
}
The above code illustrates the use of a matrix. A matrix is an array of arrays. Matrices are used for tasks
which involve a 2D or higher-dimensional representation of data. More typically, matrices are used for tasks
in data which undergoes successive changes, such as in simulations; or in encryption and other applications
where data values must undergo in-place swaps. Like arrays, matrices can be of any type (int, char, string,
boolean, etc.).
Lines 8-13 illustrate the declaration and initialization of a matrix A. As with arrays and other variables, the
type is first given, followed by the variable name. Rather than one set of brackets, there are two; each set
is to index elements Aij within the matrix. At initialization, the row and column sizes are given inside the
brackets to indicate the size of the matrix. Those sizes N and M are defined in macros on Lines 4-5. This
is an 4x5 matrix; that is, it has 4 rows and 5 columns.
Lines 9-12 contain the matrix data. Each row is, in fact, an array of size 5. There are 4 such arrays, each of
which is comma-separated. The outermost braces correspond to the bounds of the outer array. As with any
initialization statement, it ends with a semicolon.
Following this, counters i and j are declared. Then the matrix is looped over. Index i loops in the range
[0, N ); that is, the rows. Index j loops in the range [0, M ); that is, the columns. For each element Aij A,
we print it out. After the inner loop over columns, we print out an endl to break the line so that for the
next row in the matrix, printing resumes on the next line.
101
2,
5,
3,
1,
4,
2,
5,
2,
3,
1,
4,
5,
5} ,
4} ,
1} ,
3}
};
cout << " Original :\ n \ n " ;
print_matrix ( a );
scalar_mul (a , 2);
cout << " \ n \ nScalar multiplication :\ n \ n " ;
print_matrix ( a );
return 0;
}
The above code illustrates scalar multiplication with a matrix A and scalar = 2, it computes A via a
function scalar mul.
The function scalar mul simply computes aij 2aij . Observe that scalar mul does return a value, yet
changes to the matrix is printed. This is because matrices, being arrays, possess the same property of having
their changes effected when passed as arguments to arrays, even without the address-of operator (&).
102
2,
5,
3,
1,
4,
2,
5,
2,
3,
1,
4,
5,
{3 ,
{1 ,
{4 ,
{1 ,
{2 ,
5,
2,
1,
4,
3,
2,
4,
2,
3,
5,
1} ,
3} ,
5} ,
5} ,
4}
5} ,
4} ,
1} ,
3}
};
int B [ M ][ N ] = {
};
int C [ N ][ N ];
cout << " A :\ n \ n " ;
print_matrix ( A );
cout << " \ n \ nB :\ n \ n " ;
print_matrix ( B );
matrix_mul (A , B , C );
cout << " \ n \ nA * B :\ n \ n " ;
print_square ( C );
return 0;
}
void print_matrix ( int A [ N ][ M ]) {
int i , j ;
for ( i =0; i < N ; i ++) {
for ( j =0; j < M ; j ++) {
103
cout << setw (4) << A [ i ][ j ];
}
cout << endl ;
ABij =
N
X
Aik Bkj .
That is, for each element ABij in the resulting matrix, take the dot product of the column of A and the
row of B.
104
2,
5,
3,
1,
4,
2,
5,
2,
3,
1,
4,
5,
5} ,
4} ,
1} ,
3}
};
print_matrix ( A );
return 0;
}
The above code prints the matrix in the previous example, except it uses a function to do so. Moreover, it
omits the macro definitions of N and M.
This code illustrates an important quirk of C matrices: when passing matrices to a function, the sizes of the
matrix must be specified in the paramter list. Therefore unless the sizes are defined as macros, their sizes
must be hard-coded in the parameter listing in place of N and M.
This poses quite an inconvenience when the size of the matrix is not known at compile time (e.g. if one
wishes to read the contents of a file into a matrix). As we will see later, advanced data types in C++ allow
us to avoid this awkward hard-coding.
105
106
ATji = Aij .
That is, for each element, flip the indices. Or, make the rows into columns and the columns into rows.
This principle is captured on Line 11, when a matrix A is copied into B except that the indices have been
switched. Notice that A is N xM , but B is M xN .
107
108
Chapter 11
Structs
109
This program illustrates struct for creating unique data types. In particular, it creates a data type for
storing information about a video game character.
Lines 5-8 are a struct definition for a struct data type called character. Syntax for a struct definition is as
follows:
struct name {
// Data fields
};
Whatever data fields which are declared inside the struct are associated with the struct. On Line 6, integers
hp and mp are declared, and on Line 7, a string name is declared.
Now variables of the new struct data type can be declared. Line 11 declares a struct variable called dc of
type character. Lines 12-14 initialize the data for dc using the dot operator (.). Syntax of accessing
fields of the struct is as follows:
structvarname.fieldname
Thus the hp of dc can be accessed with dc.hp, and set with dc.hp = 100;. Likewise can dc.mp and dc.name
be set (Lines 13-14). For the purpose of output, data values of these fields may be treated in the same way
(Lines 15-17).
110
rand ()%3;
rand ()%20;
rand ()%10;
<<
<<
<<
<<
endl ;
endl ;
endl ;
endl ;
This is an example of a struct array. The objective of this program is to create a randomized character party
from characters with fixed names.
A struct character is defined with three integers hp, mp, lvl and string name, to represent a video game
character (Lines 9-12).
111
112
Chapter 12
Recursion
113
This code demonstrates recursion, or the process whereby a function calls itself. This particular code is an
example of infinite recursion, wherein a program calls itself indefinitely because it lacks a stopping condition,
or has a stopping condition which is never true.
In the code, the function hello is recursively defined with an empty parameter list (Line 4). The function
simply prints out Hello, world! with a newline (Line 5), then calls itself (Line 6). The program control
passes back to the beginning of the function (Line 4), then prints out Hello, world! with newline again
(Line 5), then calls itself (Line 6) . . . This continues indefinitely.
114
This program recursively counts upward from 0 in steps of 1, infinitely. Program control begins with a call
to the function count (Line 10), which has its parameter i initially at 0 (Line 4). It outputs the value of
i and calls count, i.e. itself, with the argument i+1, that is the value of i plus 1. This passes 1 to count,
which prints out 1, then calls count again with argument i+1, that is 2.
This process repeats indefinitely until the call stack undergoes what is known as a stack overflow. Each
call to count is stored on a call stack, or data structure which holds the order in which the function calls
were made. When the computer runs out of memory and cannot allocate more to hold the information on
a new call, the program seg faults and quits.
115
This code illustrates a recursive implementation of summation, for which we have already seen an iterative
or dynamic programming approach.
The program begins by calling sum(1, 5) (Line 10). This returns the value 1 plus the return of sum(2, 5)
(Line 6), which in turn returns the value 2 plus the return of sum(3, 5), . . . , plus the return of sum(5, 5),
which is 5.
Thus sum(5, 5) returns 5, then sum(4, 5) returns 4 + 5 = 9, sum(3, 5) returns 3 + 9 = 12, sum(2, 5)
returns 2 + 12 = 14, sum(1, 5) returns 1 + 14 = 15. Indeed,
5
X
i = 15.
i=1
In this recursive definition, which increases the value of i with each call, the sum is computed backwards
from 5 to 1 as the call stack reduces upon returning.
116
n
Y
= n!
i=0
using recursion. This program is similar to the count or hello functions, except the function has a condition
for stopping.
In finite recursive functions, two cases must be covered by the recursive function: a base case and a recursive
case. The base case tells the function when to stop. The base case will return something which is not a
call to the recursive function. The recursive case tells how the function calls itself, and how its return value
is affected by some combination of its inputs and the values returned by calls to itself.
A factorial can be represented as follows. Let fn represent the nth number in the factorial. Then
fn = nfn1
f1 = 1
so that f5 = 5f4 , f4 = 4f3 , . . . ; therefore f5 = (5)(4)(3)(2)(1) = 5!.
117
f1 = 1
f2 = 1
fn = fn1 + fn2
That is, for any n > 2, the nth Fibonacci number is the sum of the previous two Fibonacci numbers.
In the code, the function fib is recursively defined as a function of an integer n (Line 4). The base case will
return 1 for n 2 (Line 5) and otherwise return the sum of the previous two Fibonacci numbers (Line 6).
A test of the program is provided (Line 10).
118
This program is an iterative or dynamic programming approach to generating the Fibonacci sequence
using the formulas
f1 = 1
f2 = 1
fn = fn1 + fn2
The function fib (Line 4) initializes fn1 and fn2 to 1. These are variables to hold the previous and next
previous Fibonacci numbers. A loop (Line 6) ranges i from 3, the third Fibonacci number, up to the given
n, or the nth Fibonacci number that we wish to compute. For each iteration it computes the new number
based upon the previous two, then shifts the values of the previous two to their next-previous counterparts
(so that fn1 fn and fn2 fn1 ) for the next iteration.
119
int main () {
a (0);
return 0;
}
This program illustrates indirect recursion; that is recursion, but wherein a function does not call itself
per se; instead it calls other functions which (eventually) call the original function again, passing program
control to the beginning of the calling function.
In this example a calls b and b calls a. This process continues indefinitely, since there is no condition to stop
it.
120
Appendix A
Problem Sets
Contents
A.1 Problem Set 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
A.2 Problem Set 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
A.3 Problem Set 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
A.4 Problem Set 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
121
A.1
Problem Set 1
122
1. [20] Hello, world! L. 1 Application (Computer Science). Write a program that prints
Hello, world!
to the screen. The output must be character-for-character identical: with correct spelling [2x2], punctuation
[2x2], and capitalization [2x2]; a newline should be printed afterward [4]. It should return 0 [2] and do
nothing else [2]. Name the source file hello-world.cpp [-5]. As with all programs, it must compile [-10]
and be free of run-time errors [-10].
x : _
f : _
f: _
where
is the output.
Use setw(8) and setprecision(2) for f and f 0 .
difference-approx.cpp [-5].
123
i.
j=1 i=1
(where
Also write another program which can, given a sum of a product generated in this fashion, find n.
followed by a newline [15]. Call this
Prompt with Enter sum of product:
and output n is
reverse-sum-of-product.cpp [-5].
3. [40] If and Boolean Logic L. 4 Application (Computer Science). I have a code which accepts boolean
values a, b, and c as input, in that order, with no prompt. Once entered, it executes the following pseudocode:
If c is true, flip the value of a.
Then if b is true, flip the value of c.
Then if a is true, flip the value of b.
It then outputs abc. Write a code that accepts the output of my code and derives the original abc. Use only
three boolean variables and output the solution as specified [10]. For full credit the solution must use only
three conditionals and three flips [30=3x10]. Program interaction looks like:
> 1 0 1
< 1 1 0
124
A.2
Problem Set 2
125
1. [20] Strings, Library Functions L. 2 Application (Linguistics). Translate the following pseudocode into
C++ code. Let s be a string input through stdin in main [2]. Make functions swap [4] and reverse [8], and
include their prototypes [2=2x1]. Above each function in multi-line block comment, provide a one-sentence
comment which gives a brief description of what it does [2=2x1]. Use the variable names in the pseudocode
[2]. Use unistd.h for time functions and string() to clear the screen. Use std::flush to flush standard
output before each wait time inside the for-loop. Call it string-reverse.cpp [-5].
Where
string
1. Let S size(s).
2. Clear the screen.
3. Output s.
4. Wait for 1 second.
5. For i in the range [0, S/2):
(a) Clear the screen.
(b) Swap(s[i], s[S i 1]).
(c) Output s and end line.
(d) For all characters j in the range [0, S 1]:
i. If j = i or j = S-i-1, print a caret ().
ii. Else print a space.
(e) Wait for 500 milliseconds.
6. Wait for 1 seconds.
7. Return s.
126
2. [30] File I/O: L. 3 Application (Chemistry). Write a program which accepts two strings a and b from
stdin [4] each representing the names of two distinct ionic particles to undergo an ionic bonding into a single
product. The program should then produce the reaction equation. Use a provided dictionary D containing
entries hname, symbol, chargei to lookup the symbols and charges for names a and b.
Prompt for a with A: and b with B: [2=2x1], then output the reaction as given in the example [4]. Create
a function void react(string a, string b) [10] to output the reaction. Also write other functions: int
charge(string name) which looks up charge from the file [5] and string symbol(string name) which
looks up symbol from the file [5], each to be called by react. Document these functions with a multi-line
comment block and a one-line description per function [4]. Call the code ionic-reaction.cpp [-5]. An
example is:
A: magneium
B: sulphate
Mg + SO4 -> (Mg)2(SO4)2
Makes magnesium sulphate.
Note that if charges of -1 or +1 are exchanged, there should be no parentheses surrounding the product:
A: sodium
B: hydroxide
Na + OH -> NaOH
Makes sodium hydroxide.
Also, if the lookup fails, print that the string entered was not found in the dictionary:
A: sodiuj
B: hydroxide
sodiuj was not found in the dictionary.
Where a is the name of the first reactant, b is the name of the second reactant, and D is a dictionary
file which contains entries hn, sn , cn i: where n is the name of some reactant in D, sn is the symbol of n,
and cn is the charge of n,
define Ionic Reaction(a, b, D):
1. Lookup ca , sa , cb , sb in D.
2. Output sa + sb (sa )cb (sb )ca .
3. Output Makes a b.
127
3. [50] Functions and Libraries L. 4 Application (Music, Physics). Write a library of functions to compose
music from raw sound data. Write functions:
Define these [2x15] in a file sound.cpp. Also write a header file sound.h [5], example usage example.cpp
which writes to a file sound.raw [5], and a Makefile to compile the library as well as the example, complete
with a clean rule [5]. Create the functions in a namspace called snd. Document the two library functions
[4=2x2] and the example [1] by writing one-sentence descriptions in multi-line comment blocks above the
function definitions.
The function wave will generate a sound wave given any frequency f at time t. Include unistd.h to make
the function of type uint8 t. The function to generate a sound wave is:
A(f, t) = Asin(
2f t
)
R
Let the volume constant A = 127, the sampling rate R = 8000, and phase shift = 0.
Additionally a function freq will tell the frequency of any musical note entered as a string in scientific pitch
notation. It will contain the note (as a character A-G), an optional flat/sharp indicator (b, #, or nothing),
followed by an octave (integer 1 to 8), in that order. Examples include:
Calculate the frequency by parsing the string note and using the formula:
fn = f0 (a)n
where f0 is the frequency of a fixed note, a = 2 12 , and n is the number of half-steps or semitones away from
the fixed note fn is. Use f0 = 440 Hz for A4 . Be sure to name all the files correctly [-25=5x-5].
128
A.3
Problem Set 3
129
1 10 1
4 5 6 7 8 9 10
1 10 1
1 3
Call this program x -interpreter.cpp, where x is one of seq, word, or html, after the library you are
writing the interpreter for [-5].
130
3. [30] Arrays and Files L. 4 Application (Psychology). Your task is to find (a) the person in the class
who is most similar to you and (b) the person in the class who is most different from you. The data file
D, or neo-ffi.dat, contains personality data from your classmates in the form of N size-10 vectors. First,
identify your entry and delete it from the file. Then load your entry vector x into a size-10 array and the
data from D into a matrix P ; then compute the Manhattan distance between your vector x and each
vector yj P ; that is
10
X
|xi yji |.
Load these distances into an array of size N . Then use functions argmin and argmax to find the indices of
the most similar and most different vectors, respectively; that is
10
X
arg min
|xi yji | , yj P
j
10
X
arg max
|xi yji | , yj P
j
Similar:
1 3 2 4 5 4 3 2 1 2
Different: 5 5 5 1 2 1 1 5 5 4
be sure to align them, like so [2x5]. Create [3x5] and use [5] the functions
int argmin
(int x[N]);
int argmax
(int x[N]);
int manhattan(int x[N], int y[N]);
4. [40] Matrices, Boolean Logic L. 5 Application (Biology). You will implement a simulation of cellular
life, i.e. a cellular life automata, as per the rules in Conways Game of Life.
You will create a board B of size N xM , where N = 65 and M = 20, of type boolean. To initialize the board,
for each element bij B, set bij to 1 with 10% probability, 0 otherwise. You may do this using the rand()
function from cstdlib and a modulus operation. Initialize the board inside a function init board.
For each iteration in the evolution of the board, create the next board as follows:
If n > 3: bij 0.
Else if n > 1 and bij = 1: bij 1.
Else if n < 2: bij 0.
Else if n = 2 and bij = 0 : bij 1.
You will need to copy the board beforehand in order to ensure the integrity of the checks in the if-elseif-else
structure.
After obtaining the next board, print the board, wait 60 ms, and clear the screen for the next iteration
[8]. Every 50 iterations, disinfect the board; that is for all bij B, let bij 0 with probability .5. Write
functions [30=5x6]:
int
moore
(bool x[N][M], int i, int j);
void init_board(bool x[N][M]);
void next_board(bool x[N][M]);
void print_board(bool x[N][M]);
void clean_board(bool x[N][M]);
Inside main, make a call to init board, then loop over calls to next board and print board and the
occasional clean board.
Name the file conway.cpp [-5].
132
A.4
Problem Set 4
133
[20] Expressions, Arrays L. 2 Application (Mathematics). Write a program to compute the cross product
of two vectors ~u = hu1 , u2 , u3 i and ~v = hv1 , v2 , v3 i, that is ~u ~v = hw1 , w2 , w3 i, using the equations
w1 = u2 v3 u3 v2
w2 = u3 v1 u1 v3
w3 = u1 v2 u2 v1
Give the user a prompt u> , then read 3 integers. Also prompt with v> and read 3 integers. Write a
function cross(int u[], int v[], int w[]) which does a cross product of ~u and ~v and stores the result
in w.
~ Then output the result like so:
w< 3i + 4j - 5k
Name this cross-product.cpp [-5]. If you want, create a library [+20] and interpreter [+20] for the functions int add(int u[], int v[], int w[], int n), int dot(int u[], int v[], int n) and void
cross(int u[], int v[], int w[], int n) for use with vector problems. For dot and add, you will
need to have the user enter n (the function cross will only support n = 3). Interaction looks like:
> dot 3
> 1
> -2
> 3
< ok
> 1
> 3
> 2
< ok
< 1
[20] Loops, Functions L. 2 Application (Physics). Simulate the throwing of a ball into the air using the
parametric equations:
x(t) = t,
y(t) =
t2
t + 25,
60
on an ASCII gride of size 25x60. Define macros N = 25, M = 60. Modify print board from
ball-bounce.cpp to print a ball at x, y coordinates defined by the equations. Sleep for 60 ms in between each call to print board. Name this ball-throw.cpp [-5]. For a little extra challenge [+10], throw
the ball back and forth indefinitely until the program is killed.
134
[20] Loops, Functions L. 2 Application (Chemistry). Solve for pressure of one mole of gas under multiple
possible volumes and temperatures as dictated by the ideal gas law :
P (V, T ) =
RT
.
V
Define functions
[20] Loops, Strings L. 2 Application (Biology). In the body of a main function which is 15 lines or less,
perform RNA transcription on a user-supplied string of RNA nucleotides. Give a prompt > , then allow the
user to enter a string. Output the DNA transcribed form after a < .
> UCGACAUGU
< AGCTGTACA
Loop over the string and make the transcriptions: U A, G C, C G, A T . If the string contains
any letters other than U, C, G, or A, then output an error message that says X is not a nucleotide. and
exit with status code 1. Name this transcribe-rna.cpp [-5].
To get more use out of it [+20], copy each three-letter sequences into a codon array and look up the codon
in the file dna-codons.dat to get the amino acid that it codes for, then output it. Output for the above
looks like:
AGC Ser
TGT Cys
ACA Thr
135
[20] Selection Structures, Arrays (Psychology). Write a program which gives a condensed Myers-Briggs
test to guess the users Myers-Briggs type. At startup, print out:
On a scale of 1-7:
1 (strongly disagree), 2 (disagree), 3 (slightly
disagree), 4 (neutral), 5 (slightly agree), 6 (agree), 7 (strongly agree), rate
the extent to which you agree/disagree with the following statements:
Then ask the following 8 questions, and store the answers into a size-8 integer array or answer vector ~a:
1).
2).
3).
4).
5).
6).
7).
8).
I
I
I
I
I
I
I
I
Where indexing starts at 1, use the following logic to determine the typology from the response set:
Example output: You are an INTJ! or You are an ESXP!. Name this program myers-briggs.cpp [-5].
For some more fun [+20], transcript the resulting string to its opposite counterpart, e.g. for the above, The
opposite is an ESFP! or The opposite is an INXJ!. For yet more fun [+20], log all the raw numeric
responses entered into a file called myers-briggs.dat for your later perusal. Each line should have 8
space-delimited entries.
[20] Selection Structures, Loops L. 2 Application (Electrical Engineering, Philosophy). Where the body
of your main function is 15 lines or less, show that De Morgans laws
1. (p q) p q
2. (p q) p q
are true by exhausting combinations of hp, qi with double-for loops to obtain the truth tables for them.
Output should be like the following:
1.) p:0,
p:0,
p:1,
p:1,
q:0
q:1
q:0
q:1
:
:
:
:
1
1
1
1
You will need to declare p and q as integers to loop them over [0, 1]. Name this de-morgan.cpp [-5].
(Once you have the solution, you will be able to obtain truth tables for other boolean expressions by editing
136 generate similar truth tables for modus ponens
the conditionals. ;) If you want more practice [+10],
(p q, p ` q) and modus tollens (p q, q ` p).
[25] Boolean Logic, Library Functions L. 3 Application (Computer Science). Write a program to deal
a poker hand. It should deal 5 cards from a deck of 52, and should not deal the same card twice. Output
should look like:
5
J
10
2
3
of
of
of
of
of
hearts
spades
diamonds
clubs
hearts
It should support jacks (J), queens (Q), kings (K), and aces (A). Name this poker-dealer.cpp [-5]. For a
challenge [+20], allow the use of only one unsigned long long integer variable throughout the whole program;
represent the dealt cards using bitwise operators and powers of 2.
137
[40] Loops, Libraries, Arrays L. 4 Application (Music, Language, Computer Science). Using code and
ideas from the library libsound, write a program which generates a song from a string of characters (a word
or sentence) [40]. Write a function void play string(string str) which plays each character in the string
for some duration d of your choosing. Map the characters [a-z] and [A-Z] to an n of 1-52, where n is the
number of semitones above A4 . Also, let a space be a rest for d. Test it in main with two words that rhyme
and contain similar letters [5]. Name this play-words.cpp [-5].
For some extra fun [+20], put void play string(string str) into libsound and then write an interpreter for it that supports both functions void play(string note, float duration) and void
play string(string str) so that you can play whatever you want to file.
[60] Matrices L. 4 Application (Earth science). As a general rule, rainfall drains from higher-elevation
areas to lower-elevation areas. Given elevation data, one could obtain a vector field of directional flow
of rainwater on the Earths surface at the start of a rainshower. Your task is to obtain the vector field of
rainwater drainage on dry land for the city of Baton Rouge.
You are given a data file baton-rouge.dat containing fields hlongitude, latitude, elevationi, or h, , ri; or,
when approximated as a uniform grid, hx, y, zi. The xy component grid is N xN . For any point (xi , yi , zi ) on
the grid, first calculate the differences zi zj for all four points zj in the von Neumann Neighborhood of
zi ; then let the directional vector vi be the direction given by the maximum difference. If all the differences
are negative, then the point at i is a sink ; that is, water drains to this point and cannot runoff because there
is no lower-elevation area in the neighborhood.
Let any vi be indicated by an ASCII symbol corresponding to its direction (> < ^ v). If i is a sink point,
indicate it with an asterisk (*). Load these into a matrix of type char and print them to stdout. Name this
program rainfall.cpp [-5].
138
[80] Matrices (Physics). L. 5 Application Modify ball-bounce.cpp to populate the board with multiple
balls, and detect and handle any collisions between two balls when they occur.
Initially, for each point aij on the board, a ball will be spawned with .1 probability, for an average of 10%
density. The x and y momenta will range from [-1, 1] (thus it is possible for a ball to begin stationary).
For each iteration in the evolution of the board, for each position aij , if aij contains a ball, check its direction
and find the cell b it will be in at the next iteration. If there is a ball in b which is stationary, then on the
next iteration aij will halt and b will inherit the momentum of aij . If b does not contain a stationary ball,
but one moving opposite to aij , they will both halt upon the next iteration and swap momenta.
Otherwise, check the Moore neighborhood of b to see if any other ball exists such that its direction lands it
in b on the next iteration. If such a ball does exist, a and b collide.
Upon a collision, the law of conservation of momentum determines the new momenta of the two balls. That
is, the x and ycomponent momenta must be preserved. Note that you only need to handle collisions of
two balls; if more than two balls would collide on the next iteration, handle the collision case for the first
one you detect.
139
140
Appendix B
Self-Tests
Contents
B.1
Chapter 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
B.2
Chapter 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
B.3
Chapter 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
B.4
Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
B.5
Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
B.6
Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
B.7
Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
B.8
Chapter 11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
B.9
Chapter 12 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
141
APPENDIX B. SELF-TESTS
142
APPENDIX B. SELF-TESTS
B.1
B.1. CHAPTER 1
Chapter 1
[12] Binary Addition: L. 1 Application (Computer Science, Electrical Engineering). Compute 001111102
+ 000111102 . Report the answer in binary and decimal.
143
B.2. CHAPTER 2
B.2
APPENDIX B. SELF-TESTS
Chapter 2
[10] Hello, world!: L. 1 Knowledge (Computer Science). Fill in the following 5-line skeleton [5x2]. Each
underscore corresponds to exactly one character (there is exactly one correct solution). The program should
print out the string Hello, World! followed by a newline, then return a success exit code.
# _______ __________
_____ _________ ____
3
4
5
6
7
___ ______ {
____ __ _Hello , World ! _ __ ____ ;
______ __
}
[12] Variables and Expressions: L. 1 Knowledge, L. 1 Comprehension (Computer Science). Define the
following terms: variable, declare, initialize, assign [4x2]. Using the words variable, declared , initialized ,
and assigned , fill in the blanks for the following [4x1]:
A
can be
a value.
144
APPENDIX B. SELF-TESTS
B.2. CHAPTER 2
[11] Variables and Expressions: L. 1 Knowledge, L. 1 Comprehension (Computer Science). Define the
following terms: operator , increment, decrement, and expression [4x2]. Using the words operator , expression,
increment, and fill in the blanks for the following two sentences [3x1]:
The
[11] Variables and Expressions: L. 1 Knowledge, L. 1 Comprehension (Computer Science). Define the
following terms: operator , increment, decrement, and expression [4x2]. Using the words operator , expression,
increment, and decrement, fill in the blanks for the following two sentences [3x1]:
If I start with 0 then and I end up with 0.
A binary arithmetic on two variables forms an .
145
B.2. CHAPTER 2
APPENDIX B. SELF-TESTS
[10] Debugging: L. 2 Comprehension (Computer Science). The following main method block has one syntax
error per line (except the return statement). Fix each bug, giving the correct code to the right-hand side
[10=5x2].
[10] Operators, Expressions: L. 2 Comprehension (Mathematics). If the input to the following code is 2,
what is the output [6]? If the output from the following code is 4, what was the input [4]?
146
APPENDIX B. SELF-TESTS
B.2. CHAPTER 2
[10] Boolean Operators, Boolean Logic: L. 2 Comprehension (Philosophy). Print the program output
[8=4x2]. Mind the formatting [2].
<<
<<
<<
<<
",
",
",
">
";
";
";
";
147
B.2. CHAPTER 2
APPENDIX B. SELF-TESTS
[12] Bitwise Operations: L. 2 Application (Electrical Engineering). Compute 85 170 & 1. Convert each
number to binary [6], then perform the two bitwise operations [4] and convert back to decimal [2].
148
APPENDIX B. SELF-TESTS
B.3
B.3. CHAPTER 3
Chapter 3
[8] If-Elseif : L. 1 Comprehension (Biology). Print the output for of this DNA-to-RNA transcriptor for
input cases hC, A, T, Gi [4x2].
Code B.3-6: If
1
2
3
4
5
6
7
8
9
10
11
12
A )
C )
G )
T )
cout
cout
cout
cout
<<
<<
<<
<<
U ;
G ;
C ;
A ;
b;
b;
== 2* a + 2) cout <<
== 2* a
) cout <<
== 2* a - 2) cout <<
cout <<
149
B.3. CHAPTER 3
APPENDIX B. SELF-TESTS
[10] Switch: L. 2 Comprehension (Computer Science, Mathematics). What happens when I put in a values
of h1, 2, 3, 4i?
3
4
5
6
7
8
9
10
11
12
13
14
int main () {
int
a;
cin >> a ;
switch ( a ) {
case 1 : a
case 2 : a
case 3 : a
default : a
}
return 0;
}
= a;
break ;
= -a /2; break ;
= a /2; break ;
= -a /4; break ;
[10] If : L. 2 Comprehension (Psychology). The following toy code accepts an (integer) number (a Likert
scale response of 1-7) and prints out emoticons based upon the response. What is printed when the response
is h1, 2, 3, 4, 5, 6, 7i [7]? What about 8 [2]? Is it possible to enter an integer that yields no output [1]?
response ;
if ( response >
if ( response >
if ( response <
if ( response <
if ( response <
150
APPENDIX B. SELF-TESTS
B.3. CHAPTER 3
[10] If-Else, Boolean Logic: L. 3 Comprehension (Electrical Engineering). If h1, 0, 1i are put in, what
is output [3]? If the output is 1010, what values of a, b, and c must have been put in [4]? Identify one
impossible 4-digit binary output [3].
[10] Nested If-Else: L. 3 Comprehension (Philosophy). What does the following program print [10]?
if
( false )
else
else
if
( true )
else
if ( false ) if
( true )
else
else
if
( false )
else
if ( true )
if
if
( true )
( false )
else
if ( false ) if
if
else
false );
true );
! true );
true );
! true );
false );
cout << (
true &&
true );
cout << (
true &&
! true );
false );
else
else
true &&
else
else
cout << (
cout << (
( false )
true );
! true );
false );
return 0;
}
151
B.4. CHAPTER 4
B.4
APPENDIX B. SELF-TESTS
Chapter 4
[9] For: L. 1 Knowledge (Computer Science) Name [3x1] and define [3x2] the three statements which control
a for-loop.
[9] For: L. 1 Knowledge (Computer Science). What is an iteration and an accummulator [3x2]? In the
following code, circle the accumulator [3].
152
APPENDIX B. SELF-TESTS
B.4. CHAPTER 4
[10] For: L. 1 Knowledge (Computer Science). Answer the following true/false [5x2].
For-loops have three statements in addition to a body.
Every for-loop and while-loop needs braces.
For-loops can be nested inside for-loops.
Parentheses can be omitted from a for-loop.
153
B.4. CHAPTER 4
APPENDIX B. SELF-TESTS
[16] For: L. 2 Knowledge (Mathematics). The following code should print the sum from a to b in steps of j.
Fill in the skeleton [8x2].
[14] For: L. 2 Knowledge, L. 1 Comprehension (Mathematics). The following code should print a 1x10
multiplication table. Fill in the for-loop parameters [2x6 or 3x4] and remainder of the skeleton [2x2].
154
APPENDIX B. SELF-TESTS
B.4. CHAPTER 4
[10] For/Debugging: L. 2 Comprehension (Computer Science, Mathematics). The following code should,
when a number i is input, compute
10
X
3;
and, it will output the value 10 followed by a colon and the value of the computed sum. However in main
body of the following code, I made 5 logical errors on Lines 6-10, one per line. Exactly one character per
line (including spaces) may be switched to correct the program (characters can also be switched for spaces).
Circle those characters [5x1] and give their replacements [5x1].
[15] For/While: L. 2 Comprehension (Physics, Music). Certain wine glasses will break when exposed to
their resonance frequences, which are typically in the range of 800-1600 Hz. The following code snippet will
play a sound wave whose frequency f increases from 800 Hz to 1600 Hz in steps of 1. What are the lowest
[3] and highest [3] values that t can be? What are the lowest [3] and highest [3] values the expression on
Line 6 can take? For how long does the song play [3]?
155
B.4. CHAPTER 4
APPENDIX B. SELF-TESTS
[10] For/Debugging: L. 2 Comprehension (Computer Science, Mathematics). The following code should,
when a number i is input, compute
10
X
3;
and, it will output the value 10 followed by a colon and the value of the computed sum. However in main
body of the following code, I made 5 logical errors on Lines 6-10, one per line. Exactly one character per
line (including spaces) may be switched to correct the program (characters can also be switched for spaces).
Circle those characters [5x1] and give their replacements [5x1].
[16] For: L. 3 Comprehension (Computer Science). Where there are infinite loops, label them with . For
all finite loops, write the value of i printed [8x2].
for
for
for
for
for
for
for
for
156
APPENDIX B. SELF-TESTS
B.4. CHAPTER 4
[15] Loops: L. 1 Application (Computer Science, Linguistics). The following English-style pseudocode
below is a verbatim in-class reading of one of my C++ codes. Translate it back into C++ [15].
cin n
for i equals one, i less than or equal to n, i plus plus
if n modulus i double-equals zero
cout i
[10] Loops: L. 1 Application (Philosophy). Write a for-loop that never starts [5] and a for-loop that never
ends [5].
157
B.4. CHAPTER 4
APPENDIX B. SELF-TESTS
[15] Loops: L. 2 Application (Art). The code below types out 0s and 1s to the screen. Modify Line 8 to
print the ASCII characters a-z (encoded by integers 97-122) to the screen indefinitely. Hint: use a typecast.
[20] For: L. 3 Application (Computer Science). Using your knowledge of binary translation, write a short
program that accepts some integer 0 n 255 and translates it into binary [20].
158
APPENDIX B. SELF-TESTS
B.5
B.5. CHAPTER 5
Chapter 5
[9] If-Else/For: L. 2 Comprehension (Mathematics). Give the output of the following code snippet for
inputs of a equal to -3, 3, and 0 [3x3].
int
a;
cin >> a ;
if (a >0) for ( i =1; i <= a ; i ++) cout << i << " " ;
else if (a <0) for ( i = a ; i < 0; i ++) cout << i << " " ;
else
cout << a ;
cout << endl ;
[10] For/For/If : L. 3 Comprehension (Mathematics). What does the following print for x = 8 [2]? For
which numbers x is there no output [4]? For which numbers y is there no output [4]?
159
B.5. CHAPTER 5
APPENDIX B. SELF-TESTS
[10] Do-While/If-Else: L. 2 Comprehension (Computer Science). From the following code snippet, what
is output when I put in c values of h1, 0, 1i [4x2]? Is it possible to input a number that does not lead to
any output [2]?
[8] If/If : L. 2 Comprehension. (Electrical Engineering). What does the following print for abc inputs of
h111, 110, 101, 011, 100, 010, 001, 000i?
bool
a,
cin >> a ; cin >>
if ( a ) if ( b )
if ( c )
if ( b ) if ( a )
if ( c )
if ( c ) if ( a )
if ( b )
b,
c;
b ; cin >> c ;
cout << " A " ;
cout << " B " ;
cout << " C " ;
cout << " D " ;
cout << " E " ;
cout << " F " ;
160
APPENDIX B. SELF-TESTS
B.5. CHAPTER 5
[14] For/If : L. 1 Application (Mathematics). The following code snippet should print the sequence
h15, 12, 9, 6, 3i, in that order; that is, the multiples of 3 in the range [15, 0). Fill in the skeleton [7x2].
161
B.6. CHAPTER 6
B.6
APPENDIX B. SELF-TESTS
Chapter 6
[10] Algorithm Design: L. 1 Application (Mathematics). Write a pseudocode or draw a flowchart for the
following code snippet:
2. [10] Algorithm Design: L. 1 Application (Mathematics). Translate the following pseudocode into C++
code:
Where
~a
~b
~c
n
:
:
:
:
vector
vector
vector
int
:
:
:
:
162
first array
second array
returned array
size of ~a
APPENDIX B. SELF-TESTS
B.6. CHAPTER 6
[16] Sorting: L. 2 Comprehension (Computer Science). Simulate the following for ~a = h2, 4, 3, 1i by creating
a 16-row table for i, j, and ~a.
2. [20] Sorting: L. 1 Application (Computer Science). Translate the following pseudocode into a C++
function. Assume all called functions are defined.
163
B.7. CHAPTER 7
B.7
APPENDIX B. SELF-TESTS
Chapter 7
[8] Call Hierarchy: L. 1 Comprehension (Computer Science). Give, in order, the names of the functions
called in the following snippet [8x2].
void
void
void
void
int
O ()
G ()
R ()
E ()
main ()
{
{
{
{
{
}
O (); }
G (); }
R (); }
E ();
return 0; }
[12] Function Calls, Chars: L. 1 Comprehension (Linguistics). For the following code snippet, print the
values of each of the six function calls [6x2].
-1);
4);
1);
-3);
-7);
19);
164
APPENDIX B. SELF-TESTS
B.7. CHAPTER 7
[8] Function Calls: L. 1 Comprehension (Mathematics). Print the outputs of the top-level function calls
in the following snippet [4x2].
int
int
int
int
add ( int
sub ( int
mul ( int
div ( int
a,
a,
a,
a,
int
int
int
int
b)
b)
b)
b)
{
{
{
{
int main () {
cout << mul ( sub (4 ,3) ,
cout << add ( mul (1 ,2) ,
cout << add ( div (4 ,3) ,
cout << sub ( add (1 ,2) ,
}
return
return
return
return
a+b;
a-b;
a*b;
a/b;
sub (2 ,1))
div (3 ,4))
mul (2 ,1))
sub (3 ,4))
}
}
}
}
<<
<<
<<
<<
"
"
"
"
";
";
";
";
[9] Function Calls: L. 2 Comprehension (Computer Science). What values of abc are output on Line 9 in
the function f [3x3]?
165
B.7. CHAPTER 7
APPENDIX B. SELF-TESTS
[12] Function Calls: L. 2 Comprehension (Computer Science). Print the output for the calls on Line 7
[3x2] and Line 8 [3x2].
[12] Function Calls: L. 3 Comprehension (Computer Science). What arguments does D pass to C, in order?
C to B? B to A [3x2]? What parameters does C receive, in order? What does B receive? What does A receive
[3x2]?
void
void
void
void
A ( int
B ( int
C ( int
D ( int
a,
a,
a,
a,
int
int
int
int
b,
b,
b,
b,
int
int
int
int
c)
c)
c)
c)
{
{
{
{
return ;
}
A (c , a , b ); }
B (b , c , a ); }
C (a , c , b ); }
int main () {
int a =1 , b =2 , c =3;
D (a , b , c );
}
166
APPENDIX B. SELF-TESTS
B.8
B.8. CHAPTER 11
Chapter 11
[10] Advanced File I/O. L. 1 Analysis (Philosophy, Computer Science). Is it possible to write a source
file which modifies itself once compiled into an executable and run? If you answer yes, sketch a diagram
showing how the process would work. If you answer no, justify your answer.
[15] Structs L. 1 Synthesis (Computer Science). Create an ontology of a person, place, or thing (e.g. video
game character, animal, etc) using a struct. Create at least 5 data fields to describe it. In a main method,
declare an instance of your struct and initialize its fields to show how it is used.
167
B.9. CHAPTER 12
B.9
APPENDIX B. SELF-TESTS
Chapter 12
[20] Structs, Recursion: L. 2 Knowledge (Computer Science). For each statement, circle true (T) or false
(F) [20=10x2].
Finite recursive functions do not require a base case and recursive case.
A push operation occurs when a function on the call stack returns a value.
A pop operation occurs when a function is called and placed on top of the call stack.
[16] Structs: L. 2 Comprehension (Mathematics). Print the output of the following [5x2]. In two brief
sentences, explain what the struct represents, what the function does [6=2x3].
B, C;
= 2.0;
= 4.0;
168
APPENDIX B. SELF-TESTS
B.9. CHAPTER 12
[10] Recursion: L. 1 Application (Mathematics). Write a recursive function count which counts from a to
b in steps of j. It should accept three integer parameters, and its return type should be void.
[10] Recursion: L. 1 Analysis (Philosophy, Psychology). Suppose a software system had a recursive function
dream with no base case. In practice, could it recurse infinitely? Regardless of your answer, justify it [5].
What about the case of a human being who dreams recursively [5]?
169
B.10. PRE-TEST 2
B.10
APPENDIX B. SELF-TESTS
Pre-Test 2
[5] Mathematical Notation: L. 1 Knowledge (Mathematics). Draw a line to match the symbol to its
meaning.
there exists
for all
such that
not
in
[5] Arrays and Matrices: L. 1 Knowledge (Computer Science). Draw a line to match the syntax to its
meaning.
a[5] = 4;
int a[4][5];
initialize array
int a[5][4];
a[4] = 5;
170
APPENDIX B. SELF-TESTS
B.10. PRE-TEST 2
[6] Libraries, Algorithms, Arrays: L. 1 Knowledge (Computer Science). Circle the correct answer. Each
is worth 2 points. Incorrect guesses earn 0 for that item, however admitting you do not know an answer
earns 1.
What is a library?
A
If a = h2, 4, 6, 8, 1, 3, 5, 9i and a0 = 2, give min, max, argmin, and argmax of a, in that order.
A
1, 9, 5, 8
4, 7, 1, 9
1, 9, 4, 7
5, 8, 1, 9
171
B.10. PRE-TEST 2
APPENDIX B. SELF-TESTS
[9] For, Files, Arrays: L. 3 Knowledge (Computer Science). Circle the correct answer. Each is worth 3
points. Incorrect guesses earn 0 for that item, however admitting you do not know an answer earns 1.
for(;;);;
for(;;);
for(;;)
for();
ofstream
ifstream
iostream
Both A and B
Given that initially i = 0, one of the following lines correctly reads the total set of integers from an input
file whose handler is called infile into an array a of predetermined size n. Which is it?
A
infile >> a;
172
APPENDIX B. SELF-TESTS
B.10. PRE-TEST 2
[10] Libraries: L. 2 Comprehension (Mathematics). The stat library whose header is included in the
following code has three functions defined. Assuming the following code compiles, runs, and that the library
functions are utilized in accordance with their parameter and return types, deduce the prototypes of the
three functions from the code and write the contents of the header file below [10=3x3+1].
[15] Arrays: L. 3 Comprehension (Computer Science). At end-of-execution, the following reversible encryption code yields a = h1, 3, 5, 1, 2i. What was a originally [10=5x3]?
int n = 5;
int a [5] = {_ , _ , _ , _ , _ };
for ( i =0; i < n ; i ++) {
int j = (2* i ) % n ;
swap ( a [ i ] , a [ j ]);
}
173
B.10. PRE-TEST 2
APPENDIX B. SELF-TESTS
[15] Arrays: L. 1 Application (Mathematics). The following code obtains the first 10 Fibonacci numbers.
Translate it into a pseudocode or a flowchart.
int i , n =10 , a [ n ];
a [0] = a [1] = 1;
for ( i =2; i < n ; i ++)
a [ i ] = a [i -1] + a [i -2];
[15] Arrays L. 1 Application (Computer Science). The following poetic algorithm (written by yours truly)
describes an accelerating skyward flight. Translate it into a full C++ code.
Where
sky
higher
:
:
int
int
:
:
distance to sky
amount to increase
174
APPENDIX B. SELF-TESTS
B.11
B.11. TEST 2
Test 2
This test has three sections. You must answer the total 100 points for the first (easy) section; 200 points
from the second (intermediate) section; and 200 points from the third (difficult) section.
However, if you turned in A2#3 and/or A3#3, you must answer the corresponding L. 2 Comprehension
questions in the third (difficult) section. These count toward your 200 points for that section, leaving you
100 to choose.
For the L. 1 Application problems in the third (difficult) section, you may write a code, math-style pseudocode, or draw a flowchart; except for the (Philosophy) problem, where only a code is acceptable.
I will determine the final score from a post-hoc analysis of the test grades. After you finish the test, if you
are considering dropping the course based on your point total, mark the following box so that I may score
your test before 3:00 PM tomorrow (please do not mark the box otherwise):
B.11.1
Easy
[25] Mathematical Notation: L. 1 Knowledge (Mathematics). Draw a line to match the symbol to its
meaning [25=5x5].
exists
such that
in
not
for all
175
B.11. TEST 2
APPENDIX B. SELF-TESTS
play(note);
Makefile
A compiler
Header file
::
APPENDIX B. SELF-TESTS
B.11. TEST 2
[25] Loops: L. 1 Knowledge (Computer Science). Fill in the correct answer [25=5x5].
initialization statement
condition
update statement
Which of the following statements does not break out of a loop assuming it resides in a function of type
void?
A
break;
false;
exit(1);
return;
B.11. TEST 2
APPENDIX B. SELF-TESTS
[25] Arrays: L. 1 Knowledge (Computer Science). Fill in the correct answer [25=5x5].
In which situation are brackets not required with a built-in C++ array?
A when receiving the array as a parameter
B
[0, n]
C [1, n)
D [1, n]
an integer
C a string
D a function
a file
C an integer
D a function
178
APPENDIX B. SELF-TESTS
B.11.2
B.11. TEST 2
Intermediate
[50] Libraries: L. 2 Knowledge (Computer Science). For each statement, circle true (T) or false (F)
[50=10x5].
The parameter names in the prototypes of a header file must be the same as the parameter
names in the function definition file.
If functions in a definition file are defined within the scope of a namespace, their prototypes
must be given within the same namespace in the header file.
The scope operator is strictly required when calling functions which are defined in a namespace.
When including headers, quotes are used for C++ libraries; angle brackets are used for C
libraries.
[50] Arrays: L. 2 Knowledge (Computer Science). For each statement, circle true (T) or false (F) [50=10x5].
If functions in a definition file are defined within the scope of a namespace, their prototypes must be
given within the same namespace in the header file.
The scope operator is strictly required when calling functions which are defined in a namespace.
When including headers, quotes are used for C++ libraries; angle brackets are used for C libraries.
179
B.11. TEST 2
APPENDIX B. SELF-TESTS
[50] For: L. 2 Knowledge (Mathematics). Write the code for summation from a to b in steps of j [25]; also either
write the pseudocode or draw the flowchart for it [25].
[20] Arrays: L. 1 Comprehension (Mathematics). What are the contents of b and c post-execution?
int
int
int
for
i , j , n =5;
a [ n ] = {1 , 2 , 3 , 4 , 5};
b [ n ] , c [ n ];
( i =0; i < n ; i ++) {
j = ( i + 1) % n ;
k = ( i - 1) % n ;
b [ i ] = a [ j ];
c [ i ] = a [ k ];
180
[30] Matrices: L. 1 Comprehension (Mathematics). The following code copies the first column of a into b and the
first row of a into c. Fill in the skeleton [30=15x2].
int a [ _ ][ _ ] = { {1 , 2} ,
{3 , 4} ,
{5 , 6} };
int b [ _ ] , c [ _ ];
int i ;
for ( i = _ ; i < _ ; i ++)
b [ _ ] = a [ _ ][ _ ];
for ( i = _ ; i < _ ; i ++)
c [ _ ] = a [ _ ][ _ ];
[50] Files, Matrices: L. 2 Comprehension (Mathematics). The following code words on a file called nums.dat which
contains a single row with the following:
0 1 2
3 4 5
6 7 8
Give the contents of outfile post-execution [50=9x5+5].
int i =0 , a [3][3];
ifstream infile ;
ofstream outfile ;
infile . open ( " nums . dat " );
outfile . open ( " nums2 . dat " );
while ( infile >> a [0][ i ]
>> a [1][ i ]
>> a [2][ i ]) i ++;
for ( i =0; i <3; i ++)
outfile << a [ i ][0]
<< a [ i ][1]
<< a [ i ][2];
B.11. TEST 2
B.11.3
APPENDIX B. SELF-TESTS
Difficult
[50] Libraries, Strings, Files, Arrays, Matrices: L. 3 Knowledge (Computer Science). For each statement, circle true (T) or false (F) [50=10x5].
When receiving a built-in matrix as a parameter, the sizes of all dimensions except the last
must be specified.
[50] Loops: L. 2 Comprehension (Music). You must answer this question, but only if you turned
in A2#3. Given the following prototypes for the sound library
void play(string note, float d);
float freq(string note);
float wave(float f, float t);
fill in the following skeleton. It should derive a frequency f and play for a given duration. Let the sampling
rate R be previously defined as a macro.
[50] Loops: L. 2 Comprehension (Psychology). You must answer this question, but only if you
turned in A3#3. Given that the following are defined
as well as the N M matrix p which contains personality data for each student, fill in the following skeleton
for find-person.cpp.
int
int
int
for
d [ _ ];
u [ _ ];
m [ _ ] = {1 ,2 ,3 ,4 ,5 ,1 ,2 ,3 ,4 ,5};
( i = _ ; i < _ ; i ++) {
for ( j = _ ; j < _ ; j ++) {
u [ _ ] = p [ _ ][ _ ];
}
_ [ _ ] = manhattan (_ , _ );
}
int sim = arg___ ( d );
int dif = arg___ ( d );
cout << " Similar :
";
for ( i = _ ; i < _ ; i ++)
cout << p [ ___ ][ _ ] << " " ;
cout << endl ;
cout << " Different : " ;
for ( i = _ ; i < _ ; i ++)
cout << p [ ___ ][ _ ] << " " ;
cout << endl ;
B.11. TEST 2
APPENDIX B. SELF-TESTS
[50] Loops: L. 1 Application (Philosophy). Without using any variables whatsoever, write a for-loop
that never starts [25] and a for-loop that never ends [25]. They must be syntactically correct and have
bodies, however the bodies may be empty.
[50] Loops, Strings L. 1 Application (Biology). In the body of a main function which is 15 lines or
less, perform DNA transcription on a user-supplied string of DNA nucleotides. Give a prompt > , then
allow the user to enter a string. Output the RNA transcribed form after a < .
< AGCTGTACA
> UCGACAUGU
Loop over the string and make the transcriptions: A U , C G, G C, T A. If the string contains
any letters other than A, C, G, or T, then output an error message that says X is not a nucleotide.
and exit with status code 1.
[50] Loops: L. 1 Application (Computer Science, Linguistics). The following English-style pseudocode
below is a verbatim in-class reading of one of my C++ codes. Re-write it in math-style pseudocode,
draw a flowchart for it, or translate it back into C++.
int n
cin n
bool p equals true
for i equals two, i less than or equal to square root of n, i plus plus
if n modulus i double-equals zero
p equals false
cout p
[50] Loops L. 1 Application (Psychology). Write a full program to display a message Now Open! for 1
second at a time, then flash a message Buy Coca-Cola! for exactly 300 s. It should repeat indefinitely.
Use the function usleep(unsigned int usec); from unistd.h.
[50] Loops, Functions L. 1 Application (Chemistry). The rate law for a first-order reaction is given
by
A = A0 ekt .
Write a code to accept A0 and k, then calculate A for t values of [0, 10] in steps of .1.
[50] Loops, Functions L. 1 Application (Physics). Write a main function to simulate an elliptic
planetary orbit around (x0 , y0 ) using the parametric equations
x(t) = x0 + rx cos(t),
y(t) = y0 + ry sin(t)
indefinitely. Let x0 = 30, y0 = 15, rx = 20, ry = 10. Assume the function void print board(int x,
int y); is already defined.
184
APPENDIX B. SELF-TESTS
B.12
B.12. PRE-FINAL
Pre-Final
[+8] Variables, Expressions, ADTs: L. 3 Knowledge (Computer Science). For each statement, circle
true (T) or false (F) [8=8x1]; or else circle (C) and write a code statement which, if compiled/run, could
prove the assertion true or false.
[+4] Matrices: L. 2 Comprehension (Biology). The following snippet calculates a Punnett square given
allelle encodings. Assuming print matrix is defined, print the output of the following for a of Bb and b of
Gb [4=4x1].
string a , b ;
cout << " > " ; cin >> a ;
cout << " > " ; cin >> b ;
int i , j , n = a . size () , m = b . size ();
string punnett [ n ][ m ];
for ( i =0; i < n ; i ++)
for ( j =0; j < m ; j ++)
punnett [ i ][ j ] = a [ i ]+ b [ j ];
print_matrix ( punnett );
185
B.12. PRE-FINAL
APPENDIX B. SELF-TESTS
xn+1 = xn /2.
For extra credit, explain why memory considerations prohibit infinite recursion in practice [+15].
[40] Algorithms and Code Design: L. 1 Evaluation (Computer Science). Answer the following [40=4x10].
What is the purpose of a programmatic approach to problem-solving? Give a problem scenario in which it
would be easier to write a code to solve the problem. What are the downsides to a programmatic approach?
Give another problem in which it would be easier to solve the problem by hand than write a code.
186
APPENDIX B. SELF-TESTS
B.13
Final
B.13.1
Project Evaluation
B.13. FINAL
[50] Group Project: L. 1 Knowledge (Computer Science). What was the problem your group proposed
to solve [10]? What were the roles of each member in your group [15=5x3]? Give a rudimentary sketch or
description of the solution for the problem [15].
[50] Group Project: L. 1 Evaluation (Computer Science). In your group, who participated, and how did
they participate (or not participate) [30=5x6]? Describe [10] and evaluate [10] the group dynamic.
187
B.13. FINAL
B.13.2
APPENDIX B. SELF-TESTS
Knowledge
[20] Hello, world!: L. 1 Knowledge (Computer Science). Fill in the following 5-line skeleton [20=5x4].
Each underscore corresponds to exactly one character (there is exactly one correct solution). The program
should print out the string Hello, World! followed by a newline, then return a success exit code.
# _______ __________
_____ _________ ____
3
4
5
6
7
___ ______ {
____ __ _Hello , World ! _ __ ____ ;
______ __
}
[30] Variables and Expressions: L. 1 Knowledge/Comprehension (Computer Science). Define the following terms: variable, declare, initialize, assign [4x5]. Using the words variable, declared , initialized , and
assigned , fill in the blanks for the following [4x2+2]:
A
can be
a value.
188
APPENDIX B. SELF-TESTS
B.13. FINAL
[30] Variables and Expressions: L. 1 Knowledge/Comprehension (Computer Science). Define the following terms: operator , increment, decrement, and expression [4x5]. Using the words operator , expression,
increment, and fill in the blanks for the following two sentences [3x3+1]:
The
[30] For: L. 1 Knowledge (Computer Science) Name [3x5] and define [3x5] the three statements which control
a for-loop.
189
B.13. FINAL
APPENDIX B. SELF-TESTS
[40] For: L. 2 Knowledge (Mathematics). The following code should print the sum from a to b in steps of j.
Fill in the skeleton [8x5].
[20] Call Hierarchy: L. 1 Comprehension (Computer Science). Give, the order in which the functions
called in the following snippet [5x4].
void
void
void
void
int
P ()
A ()
L ()
S ()
main ()
{
{
{
{
{
}
P (); }
A (); }
L (); }
S ();
return 0; }
190
APPENDIX B. SELF-TESTS
B.13. FINAL
[50] Libraries: L. 2 Knowledge (Computer Science). For each statement, circle true (T) or false (F)
[50=10x5].
The parameter names in the prototypes of a header file must be the same as the parameter
names in the function definition file.
If functions in a definition file are defined within the scope of a namespace, their prototypes
must be given within the same namespace in the header file.
The scope operator is strictly required when calling functions which are defined in a namespace.
When including headers, quotes are used for C++ libraries; angle brackets are used for C
libraries.
[30] Structs, Recursion: L. 1 Knowledge (Computer Science). For each statement, circle true (T) or false
(F) [30=10x3].
A push operation occurs when a function is called and placed on top of the call stack.
A pop operation occurs when a function on the call stack returns a value.
191
B.13. FINAL
B.13.3
APPENDIX B. SELF-TESTS
Comprehension
[20] Boolean Logic: L. 2 Comprehension (Philosophy). Print the program output [16=4x4]. Mind the
formatting [4].
192
<<
<<
<<
<<
" <" ;
" ," ;
" ," ;
" ," ;
" >" ;
APPENDIX B. SELF-TESTS
B.13. FINAL
b;
b;
== 2* a + 2) cout <<
== 2* a
) cout <<
== 2* a - 2) cout <<
cout <<
[40] Switch: L. 2 Comprehension (Computer Science, Mathematics). What happens when I put in a values
of h1, 2, 3, 4i [4x10]?
3
4
5
6
7
8
9
10
11
12
13
14
int main () {
int
a;
cin >> a ;
switch ( a ) {
case 1 : a
case 2 : a
case 3 : a
default : a
}
return 0;
}
= a;
break ;
= -a /2; break ;
= a /2; break ;
= -a /4; break ;
193
B.13. FINAL
APPENDIX B. SELF-TESTS
[40] If : L. 2 Comprehension (Psychology). The following toy code accepts an (integer) number (a Likert
scale response of 1-7) and prints out emoticons based upon the response. What is printed when the response
is h1, 2, 3, 4, 5, 6, 7i [7x4]? What about 8 [6]? Is it possible to enter an integer that yields no output [6]?
[60] If-Else, Boolean Logic: L. 3 Comprehension (Electrical Engineering). If h1, 0, 1i are put in, what is
output [20]? If the output is 1010, what values of a, b, and c must have been put in [20]? Identify one
impossible 4-digit binary output [20].
194
APPENDIX B. SELF-TESTS
B.13. FINAL
[40] Nested If-Else: L. 3 Comprehension (Philosophy). What does the following program print [40]?
if
( false )
else
else
if
( true )
else
if ( false ) if
( true )
else
else
if
( false )
else
if ( true )
if
if
( true )
( false )
else
if ( false ) if
if
else
false );
true );
! true );
true );
! true );
false );
cout << (
true &&
true );
cout << (
true &&
! true );
false );
else
else
true &&
else
else
cout << (
cout << (
( false )
true );
! true );
false );
return 0;
}
[40] For/Debugging: L. 2 Comprehension (Computer Science, Mathematics). The following code should,
when a number i is input, compute
10
X
3;
and, it will output the value 10 followed by a colon and the value of the computed sum. However in main
body of the following code, I made 5 logical errors on Lines 6-10, one per line. Exactly one character per
line (including spaces) may be switched to correct the program (characters can also be switched for spaces).
Circle those characters [5x4] and give their replacements [5x4].
195
B.13. FINAL
APPENDIX B. SELF-TESTS
[40] For: L. 2 Comprehension (Computer Science). Label the infinite loops with the symbol; otherwise
write the value of i which is printed after end-of-execution [40=8x5].
for
for
for
for
for
for
for
for
[50] Loops: L. 2 Comprehension (Physics, Music). Certain wine glasses will break when exposed to their
resonance frequences, which are typically in the range of 800-1600 Hz. The following code snippet will play
a sound wave whose frequency f increases from 800 Hz to 1600 Hz in steps of 1. What are the lowest and
highest values that t can be [20=2x10]? What are the lowest and highest values the expression on Line 6
can take [20=2x10]? For how long does the song play [10]?
196
APPENDIX B. SELF-TESTS
B.13. FINAL
[40] Do-While/If-Else: L. 2 Comprehension (Computer Science). From the following code snippet, what
is output when I put in c values of h1, 0, 1i [3x10]? Is it possible to input a number that does not lead to
any output [10]?
[20] Function Calls: L. 1 Comprehension (Mathematics). Print the outputs of the top-level function calls
in the following snippet [4x5].
int
int
int
int
add ( int
sub ( int
mul ( int
div ( int
a,
a,
a,
a,
int
int
int
int
b)
b)
b)
b)
{
{
{
{
int main () {
cout << mul ( sub (4 ,3) ,
cout << add ( mul (1 ,2) ,
cout << add ( div (4 ,3) ,
cout << sub ( add (1 ,2) ,
}
return
return
return
return
a+b;
a-b;
a*b;
a/b;
sub (2 ,1))
div (3 ,4))
mul (2 ,1))
sub (3 ,4))
}
}
}
}
<<
<<
<<
<<
"
"
"
"
197
";
";
";
";
B.13. FINAL
APPENDIX B. SELF-TESTS
[30] Function Calls: L. 3 Comprehension (Computer Science). What values of abcdef are output on Line
9 in the function f [6x5]? Hint: It has something to do with today . . .
[60] Function Calls: L. 3 Comprehension (Computer Science). Print the output for the calls on Line 7 and
Line 8 [30=3x2x10].
198
APPENDIX B. SELF-TESTS
B.13. FINAL
[20] Structs: L. 2 Comprehension (Mathematics). Print the output of the following [10x2].
B, C;
= 2.0;
= 4.0;
" + " << C . b << " i " << endl ;
[30] Matrices: L. 1 Comprehension (Mathematics). The following code copies the first column of a into b
and the first row of a into c. Fill in the skeleton [30=15x2].
int a [ _ ][ _ ] = { {1 , 2} ,
{3 , 4} ,
{5 , 6} };
int b [ _ ] , c [ _ ];
int i ;
for ( i = _ ; i < _ ; i ++)
b [ _ ] = a [ _ ][ _ ];
for ( i = _ ; i < _ ; i ++)
c [ _ ] = a [ _ ][ _ ];
199
B.13. FINAL
B.13.4
APPENDIX B. SELF-TESTS
Application
[30] Binary Addition: L. 1 Application (Computer Science, Electrical Engineering). Compute 101010102
+ 101010102 . Report the answer in binary and decimal.
[50] For: L. 3 Application (Computer Science). Using your knowledge of binary translation, write a short
program that accepts some integer 0 n 255 and translates it into binary [50].
200
APPENDIX B. SELF-TESTS
B.13. FINAL
[50] For/If : L. 1 Application (Mathematics). The following code snippet should print the sequence
h14, 11, 8, 5, 2i, in that order; that is, the multiples of 3 minus 1 in the range [15, 0). Fill in the skeleton
[7x7+1].
2. [40] Sorting: L. 2 Comprehension (Computer Science). Simulate the following algorithm on ~a = h2, 4, 3, 1i
by creating a 4-row table for i values of 0, 1, 2, and 3. At each iteration show j and ~a [40=4x10].
201
B.13. FINAL
APPENDIX B. SELF-TESTS
[50] Recursion: L. 2 Application (Mathematics). Write a recursive function count which counts from a to
b in steps of j. It should accept three integer parameters, and its return type should be void.
3. [40] If and Boolean Logic L. 4 Application (Computer Science). I have a code which accepts boolean
values a, b, and c as input, in that order, with no prompt. Once entered, it executes the following pseudocode:
If c is true, flip the value of a.
Then if b is true, flip the value of c.
Then if a is true, flip the value of b.
It then outputs abc. Write a code that accepts the output of my code and derives the original abc. Use only
three boolean variables and output the solution as specified [10]. For full credit the solution must use only
three conditionals and three flips [30=3x10]. Program interaction looks like:
> 1 0 1
< 1 1 0
202
APPENDIX B. SELF-TESTS
B.13. FINAL
1. [40] Strings, Library Functions L. 2 Application (Linguistics). Write a code to accept a string s and
output the reverse of it. Program interaction looks like:
> Hello
< olleH
1. [40] Strings, Files L. 1 Application (Computer Science). Write a program which generates a program
called hello-world.cpp. It should do so by opening the file hello-world.cpp for writing, and output a
Hello, world! program to it line-by-line in the form of strings. The generated code should look like this:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, world\n";
return 0;
}
203
B.13. FINAL
APPENDIX B. SELF-TESTS
[45] Libraries: L. 2 Application (Computer Science). The stat library whose header is included in the
following code is a collection of three functions. Based on their usage in the code, write curve.h [45=3x15].
204
Appendix C
Notation
205
APPENDIX C. NOTATION
Mathematical Notation
Example
Symbol
Meaning
not
=
6
=
equal to
not equal to
x=y
x 6= y
assignment
let x 1
in
xZ
there exists
x Z
for all
x Z
|
s.t.
such that
x Z | x > 0
x Z | x > 0
subscript
ai A
boldface letter
vector
matrix
a
A
~v
vector
~v = hv1 , v2 , . . . vn i
[a, b]
[a, b)
range
[1, 10]
[0, n)
206
Appendix D
Pseudocode
207
APPENDIX D. PSEUDOCODE
for
while
do
until
if
else
then
range
each
all
let
return
208
Appendix E
Algorithms
Contents
E.1
E.2
Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
E.3
Physics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
E.4
Chemistry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
E.5
Biology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
E.6
Philosophy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
E.7
Psychology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
E.8
Linguistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
209
APPENDIX E. ALGORITHMS
E.1
Computer Science
E.1.1
Manhattan Distance
Where
~x
~y
:
:
vector (int)
vector (int)
1. Let d 0.
2. Let n size(x).
3. For i in range [0, n):
(a) Let d d + |xi yi |.
4. Return d.
210
:
:
vector
vector
APPENDIX E. ALGORITHMS
E.1.2
Where
~v
vector(int)
1. Let n size(v).
2. Let min v0 .
3. For i in range [0, n):
(a) If min > vi : let min vi .
4. Return min.
Where
~v
vector(int)
1. Let n size(v).
2. Let max v0 .
3. For i in range [0, n):
(a) If max < vi : let max vi .
4. Return max.
211
E.1.3
APPENDIX E. ALGORITHMS
Where
~v
vector(int)
1. Let n size(v).
2. Let min v0 , argmin 0.
3. For i in range [0, n):
(a) If min > vi : let min vi .
(b) Let argmin i.
4. Return argmin.
Where
~v
vector(int)
1. Let n size(v).
2. Let max v0 , argmax 0.
3. For i in range [0, n):
(a) If max < vi : let max vi .
(b) Let argmax i.
4. Return argmax.
212
APPENDIX E. ALGORITHMS
E.2
E.2.1
E.2. MATHEMATICS
Mathematics
Sum
Where
int
number to sum to
1. Let s 0.
2. For i in range [0, n]:
(a) Let s s + i.
3. Return s.
213
E.2. MATHEMATICS
E.2.2
APPENDIX E. ALGORITHMS
Dot Product
Where
~u
~v
:
:
vector(int)
vector(int)
1. Let d 0.
2. For i in range [0, n):
(a) Let d d + ui vi .
3. Return d.
214
:
:
first vector
second vector
APPENDIX E. ALGORITHMS
E.2.3
E.2. MATHEMATICS
Cross Product
Where
~u
~v
w
~
:
:
:
vector(int)
vector(int)
vector(int)
1. Let w1 u2 v3 u3 v2 .
2. Let w2 u3 v1 u1 v3 .
3. Let w3 u1 v2 u2 v1 .
4. Return w.
~
215
:
:
:
first vector
second vector
~u ~v
E.2. MATHEMATICS
E.2.4
APPENDIX E. ALGORITHMS
Matrix Transposition
Where
A
B
N
M
:
:
:
:
matrix (int)
matrix (int)
int
int
:
:
:
:
matrix to transpose
matrix to transpose into
number of rows of A
number of columns of A
216
APPENDIX E. ALGORITHMS
E.3
E.3.1
E.3. PHYSICS
Physics
Where the algorithm Print Board(x, y) has been defined; and where
x
y
n
N
M
:
:
:
:
:
int
int
int
int
int
:
:
:
:
:
x position
y position
refresh rate (s)
number of rows in a board
number of columns in a board
1. Let t 0.
2. While (t 60):
(a) Let x t.
(b) Let y
2t2
N
t + M.
217
E.4. CHEMISTRY
E.4
E.4.1
APPENDIX E. ALGORITHMS
Chemistry
Where
v
t
R
:
:
:
float
float
float
:
:
:
volume
temperature
gas constant
1. Return
RT
V
Where
v1
v2
vs
t1
t2
ts
:
:
:
:
:
:
float
float
float
float
float
float
:
:
:
:
:
:
starting volume
final volume
amount to increment volume
starting temperature
final temperature
amount to increment temperature
218
APPENDIX E. ALGORITHMS
E.5
E.5.1
E.5. BIOLOGY
Biology
RNA Transcription
Where
r
d
:
:
string
string
1. Let n size(r).
2. For i in range [0, n):
(a) If ri = A0 : let di U 0 .
(b) Else if ri = C 0 : let di G0 .
(c) Else if ri = G0 : let di C 0 .
(d) Else if ri = T 0 : let di A0 .
3. Output d.
219
:
:
RNA
DNA
E.6. PHILOSOPHY
E.6
E.6.1
APPENDIX E. ALGORITHMS
Philosophy
Where
p
q
...
c
:
:
:
:
bool
bool
...
conditional to test
220
APPENDIX E. ALGORITHMS
E.6.2
E.6. PHILOSOPHY
Zenos Paradox
Where
D
d
:
:
float
float
:
:
a total distance
distance walked to
1. Let i 0, d 0, D 1.
2. While d < D:
(a) Let i i + 1.
(b) Let d d + (D d)/2.
(c) Output i, d.
221
E.7. PSYCHOLOGY
E.7
E.7.1
APPENDIX E. ALGORITHMS
Psychology
Blinking Text
Where
a
b
ta
tb
:
:
:
:
first message
second message
time to display a
time to display b
1. Clear screen.
2. Do forever:
(a) Print a.
(b) Wait for ta .
(c) Clear screen.
(d) Print b.
(e) Wait for tb .
(f) Clear screen.
222
APPENDIX E. ALGORITHMS
E.7.2
E.7. PSYCHOLOGY
Find Person
Given an N M matrix P of test data, wherein each row corresponds to a persons test vector, and each
column corresponds to a response to a test question, the following algorithm can find the most similar vector
in the matrix P to a given test vector ~v .
Where
~v
d~
P
:
:
:
vector(int)
vector(int)
matrix(int)
:
:
:
223
E.8. LINGUISTICS
E.8
E.8.1
APPENDIX E. ALGORITHMS
Linguistics
String Reversal
Where
string
string to reverse
1. Let n size(s).
2. For i in range [0, n2 ):
(a) Call swap(si , sni1 ).
3. Return s.
224
APPENDIX E. ALGORITHMS
E.8.2
E.8. LINGUISTICS
Detecting Palindromes
Where
string
1. Let n size(s).
2. For i in range [0, n2 ):
(a) If si 6= sni1 : return f alse.
3. Return true.
225
E.8. LINGUISTICS
APPENDIX E. ALGORITHMS
226
Appendix F
Flowcharts
Contents
F.1
F.2
F.3
F.4
F.5
F.6
F.7
F.8
F.9
227
F.1
APPENDIX F. FLOWCHARTS
Ball Throw
Start
Let i <- 0
Let s <- 0
Input n
false
t<=60?
true
Let t <- t + 1
Let x <- t
Let y <- t^2/60 - t + 25
Finish
228
APPENDIX F. FLOWCHARTS
F.2
Boolean Switch
false
false
Start
Input a, b, c
true
true
Finish
Output s
b=!b
229
c=!c
false
c?
b?
a?
true
a=!a
F.3
APPENDIX F. FLOWCHARTS
Cross Product
Start
Start
Input
u and v
cross(u, v)
Output w
Finish
Return
230
APPENDIX F. FLOWCHARTS
F.4
Let p <- 0
Start
false
Let p <- p + 1
p <= 1?
true
false
Let q <- q + 1
q <= 1
Let q <- 0
true
Output p, q,
!(p ^ q) <-> !p v !q
Finish
231
F.5
APPENDIX F. FLOWCHARTS
Double Summation
Let s <- 0
Let i <- 0
Let j <- 0
Input n
false
i<n?
Start
true
false
Let i <- i + 1
Let j <- 0
j<n?
Finish
true
Let j <- j + 1
Let s <- s + j
Output s
232
APPENDIX F. FLOWCHARTS
F.6
Read P critially.
Scan for relevant
information.
Start
true
Example
problem
solved?
false
Flowchart
can solve
example?
false
true
First time
solving the
problem?
true
false
Delete or insert
steps, re-draw
arrows to try to
solve example
233
Finish
F.7
APPENDIX F. FLOWCHARTS
Start
Input
v1, v2, vs
t1, t2, ts
Let v <- v1
Let v <- v + vs
v <= v2?
false
Let t <- t + ts
t <= t2?
false
true
Let t <- t1
true
Output v, t, p
Let p <pressure(v, t)
234
Finish
APPENDIX F. FLOWCHARTS
F.8
Ionic Reaction
Input a, b
Start
Output sa
sb==1?
Let ca <abs(charge(a))
Let cb <abs(charge(b))
Let sa <symbol(a)
Let sb <symbol(b)
Output sb
sa==1?
Output sa
Output sa
Output "Makes"
Output "("
Output "("
Output sb
Output a
Output sb
Output "("
Output "("
Output b
Finish
235
F.9
APPENDIX F. FLOWCHARTS
Manhattan Distance
Start
Let d <- 0
Let i <- 0
Let n <- size(x)
Input x, y
false
i<n?
true
Finish
Output d
236
APPENDIX F. FLOWCHARTS
F.10
Transposing a Matrix
Let i <- 0
Let j <- 0
Input A
false
i<n?
Start
true
false
Let i <- i + 1
Let j <- 0
j<n?
Finish
true
Output B
237
F.11
APPENDIX F. FLOWCHARTS
Start
Finish
Let r = rand()
false
true
i <= 5?
true
b[r] = true?
false
false
false
r % 13 = 0?
false
false
r % 13 = 12
r % 13 = 11
r % 13 = 10
true
true
true
true
Output A
Output J
Output Q
Output K
false
false
false
false
r / 13 = 0?
r / 13 = 1
r / 13 = 2
r / 13 = 3
true
true
true
true
Output "hearts"
Output
"diamonds"
Output
"clubs"
238
Output r
Output
"spades"
Let i <- i + 1
b[r] = true
APPENDIX F. FLOWCHARTS
F.12
Read P critially.
Scan for relevant
information.
Start
true
Example
problem
solved?
false
Pseudocode
can solve
example?
false
true
First time
solving the
problem?
true
false
Re-order, modify,
insert, or delete
steps until the
problem is solved.
239
Finish
F.13
APPENDIX F. FLOWCHARTS
false
Start
false
a?
Input a, b, c
c?
b?
false
Finish
Output a, b, c
true
true
true
b=!b
240
c=!c
a=!a
APPENDIX F. FLOWCHARTS
F.14
Reversing a String
Start
Let i <- 0
Let n <- size(s)
Input s
false
i<n/2?
true
Finish
Output s
241
swap(s[i], s[n-i-1])
Let i <- i + 1
F.15. SUMMATION
F.15
APPENDIX F. FLOWCHARTS
Summation
Start
Let i <- 0
Let s <- 0
Input n
false
i<n?
true
Finish
Output s
242
Let i <- i + 1
Let s <- s + i
APPENDIX F. FLOWCHARTS
F.16
RNA Transcription
Start
Finish
false
Input r
i < n?
Let i <- i + 1
true
false
false
false
r_i = A?
r_i = C?
r_i = G?
r_i = T?
true
true
true
true
243