Anda di halaman 1dari 243

Contents

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

10 Arrays and Matrices

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

From Algorithm to Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1.1. BINARY OPERATIONS

1.1

CHAPTER 1. INTRODUCTION

Binary Operations

The formula for binary conversion is

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.

Exercise. Convert 101011012 to decimal.


Solution:

128
1
128

64
0

32
1

+ 32

16
0
+

8
1
+

4
1
+

2
0
+

1
1
+

1 = 173

Exercise. Convert 010100102 to decimal.


Solution:

128
0

64
1

+ 64

32
0

16
1

+ 16

8
0
+

4
0
+

2
1
+

1
0
+

0 = 82

CHAPTER 1. INTRODUCTION

1.1. BINARY OPERATIONS

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).

Exercise: Add 101010102 + 010010012 .


Solution:

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

1.1. BINARY OPERATIONS

CHAPTER 1. INTRODUCTION

Exercise: Add 010101012 + 110110112 .


Solution:

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

1.2. FROM ALGORITHM TO SOFTWARE

From Algorithm to Software

Here is the process by which a program is made.


First an algorithm is developed. An algorithm is a set of instructions for performing a task. The study of
algorithmics concerns the design of efficient data structures and algorithms for accomplishing various tasks
(searching, sorting, etc.). The universal language of algorithmics is pseudocode; it is a language which all
computer scientists can read and write.
Given a task, a computer scientist develops an algorithm, or set of instructions, for solving it, and expresses
it in pseudocode. Often this involves solving sample cases of the problem, then self-examining how the
problem was solved. With knowledge of a programming language, the programmer translates the algorithm
pseudocode into source code for that language. This source code is referred to as an implementation of
the algorithm.
If the language in question
is an interpreted language,
a program called an interpreter runs the instructions
in the source code as they
are read in. If the language
is an compiled language, a
program called a compiler
translates the source code
into object code. Object
code is illegible to humans,
but contains instructions executable by the machine. Objects are linked by a linker
into an executable which
contains machine code
that is, RISC-compatible instructions which may then
be executed by the machine.
This final product is typically
what we call the program.

Definitions
algorithm

set of instructions for achieving a task

algorithmics

study of developing efficient data structures & algorithms

compiler

program which translates source code into machine


code

executable

final product; a standalone executable program

implementation

language-dependent rendering of an algorithm

interpreter

program which dynamically executes source code

linker

program which links object files with libraries to


create executable

machine code

code executable by a machine

object code

pieces of compiled (machine-language-translated)


source code

pseudocode

universal language of algorithmics

source code

instructional code for an algorithm written in a programming language

Figure 1.1: The process of program creation from an algorithm

1.2. FROM ALGORITHM TO SOFTWARE

CHAPTER 1. INTRODUCTION

10

Chapter 2

Variables and Expressions

Contents
2.1

Example Programs for the Beginner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

12

2.2

Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

15

2.3

Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

16

2.4

Boolean Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

19

11

CHAPTER 2. VARIABLES AND EXPRESSIONS

2.1

Example Programs for the Beginner

Hello, world!
Code 2.1-1: Hello World
1
2
3
4
5
6
7

# include < iostream >


using namespace std ;
int main () {
cout << " Hello , world !\ n " ;
return 0;
}

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

CHAPTER 2. VARIABLES AND EXPRESSIONS


following:

Code 2.1-2: Hello World


1 # include < iostream >
2
3 int main () {
4
std :: cout << " Hello , world !\ n " ;
5
return 0;
6 }

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

# include < iostream >


using namespace std ;
int main () {
float radius ;
cout << " Please enter the radius of a circle : " ;
cin >> radius ;
cout << " The area is " ;
cout << 3.14* radius * radius ;
cout << " . " ;
cout << endl ;
return 0;
}

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

CHAPTER 2. VARIABLES AND EXPRESSIONS


the input stream operator for inputting data from standard input into variables (or other streams).
Lines 8-12 output the area along with a message. Of particular interest is Line 9, cout << 3.14*radius;,
which outputs the result of the expression 3.14*radius*radius. An expression is a mathematical expression written in the form of a code. The code 3.14*radius*radius refers to r2 in mathematics, or the area
of a circle. Whenever expressions appear in cout statements, they are automatically evaluated and their
results are output. So 3.14*radius*radius is computed, and it is the final value of this compuation that
is output to the screen.
Line 12 demonstrates the use of endl, a C++ alternative for using the C-style \n inside of a string to end
a line. The keyword endl is part of the iostream library and the std namespace; so iostream must be
included to use it, and using namespace std; should appear in the beginning block enable the programmer
to refer to endl without explicit scoping (as in std::endl).
One way to rememeber cout << and cin >>: think of the data (for example, 3.14*radius*radius) going
into the monitor (cout), hence << is used. Likewise think of data coming from the keyboard (cin) going into
the variable (for example, radius). The output stream operator can be strung together for a more concise
rendering of the program, as in the following:

Code 2.1-4: Area of a Circle


1
2
3
4
5
6
7
8
9
10

# include < iostream >


using namespace std ;
int main () {
float radius ;
cout << " Please enter the radius of a circle : " ;
cin >> radius ;
cout << " The area is " << 3.14* radius * radius << " . " << endl ;
return 0;
}

14

CHAPTER 2. VARIABLES AND EXPRESSIONS

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

Data Types and Capacities


Bytes
Range
1 bit
2
2 bytes
65,536
4 bytes
4,294,967,295
8 bytes
18,446,744,073,709,551,615
4 bytes
3.4E-38
8 bytes
1.7E308
>=8 bytes 1.7E308

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

CHAPTER 2. VARIABLES AND EXPRESSIONS

Code 2.2-5: Aesthetic Variable Declaration


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# include < iostream >


using namespace std ;
int main () {
short
unsigned int
unsigned long

seconds ;
height ;
num_particles ;

float
double
char

pi = 3.141592;
e
= 2.718281828;
day = M ;

seconds = -36;
height =
5;
return 0;
}

2.3

Expressions

Operators and 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

CHAPTER 2. VARIABLES AND EXPRESSIONS


Expressions can be grouped with parentheses to change the order of operations. For example, in a = (5 +
3) * 2, the 5 + 3 is evaluated first to produce 8, which is then multiplied by 2 to yield 16. As in arithmetic,
our interpretation of the order of operations affects the result.
The modulo operator % is of particular interest to computer science. It finds the remainder of an integer
division. Recall dividing integers in grade school and reporting the remainder as a whole number; for example
5/2 would be reported as 2r1, or 2 with a remainder of 1. This is equivalently 2 12 . So the modulus expression
5 % 2 evaluates to 1, the remainder of integer division.
For exponentiation, there is no operator. Instead we use a function known as pow, short for power. The
function pow is called as pow(base, exponent ). base and exponent are of type double, as is the return
type of pow. So, for example, pow(2.0, 4.0) is 24 and thus evaluates to 16.0.

Truncation and Division by Zero

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

Code 2.3-6: Typecasting


1
2
3
4
5
6
7

# include < iostream >


using namespace std ;
int main () {
cout << ( double ) 5 / 2;
return 0;
}

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

CHAPTER 2. VARIABLES AND EXPRESSIONS


Compound Operators

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

CHAPTER 2. VARIABLES AND EXPRESSIONS

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

CHAPTER 2. VARIABLES AND EXPRESSIONS


Boolean expressions can be chained. Boolean operators and and or follow what are called truth tables for
evaluating expressions.

Value
0
1

And
0 1
0 0
0 1

20

Or
0 1
0 1
1 1

Chapter 3

Conditionals

Contents
3.1

If, If-Else, If-Elseif-Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

22

3.2

Switch

27

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

21

3.1. IF, IF-ELSE, IF-ELSEIF-ELSE

3.1

CHAPTER 3. CONDITIONALS

If, If-Else, If-Elseif-Else

Code 3.1-1: If-Construct


1
2
3
4
5
6
7
8
9

# include < iostream >


using namespace std ;
int main () {
bool rain = 1;
if ( rain ) {
cout << " It is raining " << endl ;
}
}

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:

Numbers or strings entered by the user

The time of day, or date of the week

Info about the machine architecture

Data in files from the machine


22

CHAPTER 3. CONDITIONALS

3.1. IF, IF-ELSE, IF-ELSEIF-ELSE

Code 3.1-2: If-Construct


1
2
3
4
5
6
7
8
9
10
11
12
13
14

# include < iostream >


using namespace std ;
int main () {
bool rain ;
bool sunshine ;
cout << " Is it raining ?
(0/1) " ;
cin >> rain ;
cout << " Is the sun shining ? (0/1) " ;
cin >> sunshine ;
if ( rain && sunshine ) {
cout << " So it s a sunshower . " << endl ;
}
}

23

3.1. IF, IF-ELSE, IF-ELSEIF-ELSE

CHAPTER 3. CONDITIONALS

Code 3.1-3: If-Else


1
2
3
4
5
6
7
8
9
10
11

# include < iostream >


using namespace std ;
int main () {
bool rain = 1;
if ( rain ) {
cout << " It is raining . "
<< endl ;
} else {
cout << " It is not raining . " << endl ;
}
}

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.

Code 3.1-4: Two Ifs


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
int main () {
bool rain = 1;
if ( rain ) {
cout << " It is raining "
<< endl ;
}
if (! rain ) {
cout << " It is not raining " << endl ;
}
}

24

CHAPTER 3. CONDITIONALS

3.1. IF, IF-ELSE, IF-ELSEIF-ELSE

Code 3.1-5: Taxes using Three Ifs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# include < iostream >


using namespace std ;
int main () {
float income , factor ;
cout << " Enter your annual income : " ;
cin >> income ;
if ( income < 9075) {
factor = .1;
}
if (( income >= 9075) && ( income <= 36900)) {
factor = .15;
}
if ( income > 36900) {
factor = .25;
}
cout << " Your tax is at least " << income * factor << endl ;
cout << " Have a nice day ! " << endl ;
return 0;
}

Code 3.1-6: Taxes using If-Elseif-Else


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# include < iostream >


using namespace std ;
int main () {
float income , factor ;
cout << " Enter your annual income : " ;
cin >> income ;
if ( income <= 9075) {
factor = .1;
} else if ( income <= 36900) {
factor = .15;
} else {
factor = .25;
}
cout << " Your tax is at least " << income * factor << endl ;
cout << " Have a nice day ! " << endl ;
return 0;
}

25

3.1. IF, IF-ELSE, IF-ELSEIF-ELSE

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 9075, let factor be .1.

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

Code 3.2-7: Grade Baseline Curving with Switch


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

# include < iostream >


using namespace std ;
int main () {
char grade ;
int baseline ;
cout << " Please enter a letter grade : " ;
cin >> grade ;
switch ( grade ) {
case A :
baseline = 90;
break ;
case B :
baseline = 80;
break ;
case C :
baseline = 70;
break ;
case D :
baseline = 60;
break ;
case F :
baseline = 50;
break ;
default :
cout << " Next time , please enter A , B , C , D , or F . " << endl ;
break ;
}
float percent = baseline /100.0;
int
curved = percent * percent *100;
cout << " The curved baseline is " << curved << " . " << endl ;
return 0;
}

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

Loops and Control Flow

Contents
4.1

For-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30

4.2

While-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

31

4.3

For-Loop Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

32

29

4.1. FOR-LOOPS

4.1

CHAPTER 4. LOOPS AND CONTROL FLOW

For-Loops

Code 4.1-1: For-Loop


1
2
3
4
5
6
7
8
9
10
11

# include < iostream >


using namespace std ;
int main () {
int i , n ;
cin >> n ;
for ( i =1; i <= n ; i ++) {
cout << i << " " ;
}
return 0;
}

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:

initialization: some variable(s) is initialized


conditional: condition under which loop repeats
increment: statement to update a variable

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

CHAPTER 4. LOOPS AND CONTROL FLOW

4.2

4.2. WHILE-LOOPS

While-Loops

Code 4.2-2: While Loop


1
2
3
4
5
6
7
8
9
10
11

# include < iostream >


using namespace std ;
int main () {
int i =0;
while ( i < 10) {
cout << i << " " ;
i ++;
}
return 0;
}

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).

Code 4.2-3: Do-While Loop


1
2
3
4
5
6
7
8
9
10
11

# include < iostream >


using namespace std ;
int main () {
int i =0;
do {
cout << i << " " ;
i ++;
} while ( i < 10);
return 0;
}

31

4.3. FOR-LOOP APPLICATIONS

4.3

CHAPTER 4. LOOPS AND CONTROL FLOW

For-Loop Applications

Code 4.3-4: Sequence


1
2
3
4
5
6
7
8
9
10
11
12
13

# include < iostream >


# include < iomanip >
# include < cmath >
using namespace std ;
int main () {
int i ;
for ( i =1; i <=10; i ++) {
cout << setw (2) << i
<< " : " ;
cout << setw (4) << pow (i ,2.0) << endl ;
}
return 0;
}

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

CHAPTER 4. LOOPS AND CONTROL FLOW

4.3. FOR-LOOP APPLICATIONS

Code 4.3-5: Function


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# include < iostream >


# include < iomanip >
# include < cmath >
using namespace std ;
int main () {
float x ;
float f ;
for ( x =0; x <=1; x +=.01) {
f = pow (x ,2.0);
if (( int )( x *100)%5 == 0)
cout << endl ;
cout << setw (4) << setprecision (2) << x << " : " ;
cout << setw (6) << setprecision (4) << f << endl ;
}
return 0;
}

33

4.3. FOR-LOOP APPLICATIONS

CHAPTER 4. LOOPS AND CONTROL FLOW

Code 4.3-6: Summation


1
2
3
4
5
6
7
8
9
10
11
12
13

# include < iostream >


using namespace std ;
int main () {
int i , n , S =0;
cout << " Enter n : " ;
cin >> n ;
if ( n < 1) return 1;
for ( i =1; i <= n ; i ++)
S += i ;
cout << " The sum is " << S << " . " << endl ;
return 0;
}

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

CHAPTER 4. LOOPS AND CONTROL FLOW

4.3. FOR-LOOP APPLICATIONS

Code 4.3-7: De-product


1
2
3
4
5
6
7
8
9
10
11
12
13

# include < iostream >


using namespace std ;
int main () {
int i , P ;
cout << " Enter product " ;
cin >> P ;
for ( i =1; P >1; i ++)
P /= i ;
cout << " n must have been " << i -1;
cout << " . " << endl ;
return 0;
}

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

4.3. FOR-LOOP APPLICATIONS

CHAPTER 4. LOOPS AND CONTROL FLOW

Code 4.3-8: Multiplication Table


1
2
3
4
5
6
7
8
9
10
11
12
13

# include < iostream >


# include < iomanip >
using namespace std ;
int main () {
int i , j ;
for ( j =1; j <=10; j ++) {
for ( i =1; i <=10; i ++)
cout << setw (4) << i * j ;
cout << endl ;
}
return 0;
}

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.

Code 4.3-9: Double Summation


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
int main () {
int i , j ;
int sum = 0;
for ( j =1; j <=10; j ++)
for ( i =1; i <= j ; i ++)
sum += i ;
cout << " The double - sum from 1 to 10 is " << sum << " . " << endl ;
return 0;
}

36

CHAPTER 4. LOOPS AND CONTROL FLOW

4.3. FOR-LOOP APPLICATIONS

Code 4.3-10: Null


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# include < iostream >


# include < iomanip >
# include < cmath >
using namespace std ;
int main () {
int
n
=
1;
float
f;
float
x
=
0;
double sum =
1;
double avg =
1;
while ( avg > .1) {
x
+= .01;
f
= exp ( - x ) * sin ( x );
sum += abs ( f );
avg = sum / n ++;
cout << x << " : " << f << endl ;
}
cout << " x is " << x << endl ;
return 0;
}

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

4.3. FOR-LOOP APPLICATIONS

CHAPTER 4. LOOPS AND CONTROL FLOW

Code 4.3-11: Forward Difference Approximation


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# include < iostream >


# include < iomanip >
# include < cmath >
using namespace std ;
int main () {
float x , f1 , f2 , d ;
f1 = pow ( -2.1 , 3.0);
for ( x = -2; x <=2; x +=.1) {
f2 = pow (x , 3.0);
d = f2 - f1 ;
f1 = f2 ;
cout << setw (10) << setprecision (4) << f1
<< " : " ;
cout << setw (10) << setprecision (4) << d /.1 << endl ;
}
}

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

# include < iostream >


# include < iomanip >
# include < cmath >
using namespace std ;
int main () {
float x , f , S = -1;
for ( x = -1+.1; x <2; x +=.1) {
f = pow (x ,3.0);
S += 2* f ;
cout << setw (10) << setprecision (2) << x << " : " ;
cout << setw (10) << setprecision (4) << S << endl ;
}
S += 8;
cout << endl << " Integral from -1 to 2 with stepsize =.1 is " ;
cout << (.1/2) * S << " using the Trapezoidal Rule . " << endl ;
}

38

CHAPTER 4. LOOPS AND CONTROL FLOW

4.3. FOR-LOOP APPLICATIONS

39

4.3. FOR-LOOP APPLICATIONS

CHAPTER 4. LOOPS AND CONTROL FLOW

40

Chapter 5

Nesting

Contents
5.1

Conditional Nesting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

42

5.2

Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

44

41

5.1. CONDITIONAL NESTING

5.1

CHAPTER 5. NESTING

Conditional Nesting

Code 5.1-1: If inside If


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# include < iostream >


using namespace std ;
int main () {
bool a , b ;
cin >> a ;
cin >> b ;
if ( a )
if ( b )
b = 0;
else
b = 1;
cout << a << " " << b << endl ;
return 0;
}

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.

Code 5.1-2: For inside If


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# include < iostream >


using namespace std ;
int main () {
bool
a;
int
i;
cin >> a ;
if ( a )
for ( i =1; i <10; i +=2)
cout << i << " " ;
else
for ( i =0; i <10; i +=2)
cout << i << " " ;
cout << endl ;
return 0;
}

42

CHAPTER 5. NESTING

5.1. CONDITIONAL NESTING

Code 5.1-3: For Inside If


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# include < iostream >


using namespace std ;
int main () {
bool
a;
int
i;
cin >> a ;
if ( a )
for ( i =1; i <10; i +=2)
cout << i << " " ;
else
for ( i =0; i <10; i +=2)
cout << i << " " ;
cout << endl ;
return 0;
}

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.

Code 5.1-4: If Inside For


1
2
3
4
5
6
7
8
9
10
11
12
13

# include < iostream >


using namespace std ;
int main () {
bool
a;
int
i;
cin >> a ;
for ( i =0; i <10; i ++)
if ( i % 2 == a )
cout << i << " " ;
cout << endl ;
return 0;
}

43

5.2. APPLICATIONS

5.2

CHAPTER 5. NESTING

Applications

Code 5.2-5: Factoring


1
2
3
4
5
6
7
8
9
10
11
12
13

# include < iostream >


# include < cmath >
using namespace std ;
int main () {
int i , n ;
cin >> n ;
for ( i =1; i <= n ; i ++)
if ( n % i == 0)
cout << i << " " ;
cout << endl ;
return 0;
}

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):

1. For each integer i from 1 to n:


(a) If n divides evenly by i, output i.

44

CHAPTER 5. NESTING

5.2. APPLICATIONS

Code 5.2-6: Boolean Crack


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# include < iostream >


using namespace std ;
int main () {
int a , b , c , d ;
for ( a =0; a <=1; a ++)
for ( b =0; b <=1; b ++)
for ( c =0; c <=1; c ++)
for ( d =0; d <=1; d ++) {
cout << a << b << c << d << " : " ;
if ( a && ! b || c && ! d ) cout << " 1 " ;
else
cout << " 0 " ;
if (! a || b && ! c || d ) cout << " 1 " ;
else
cout << " 0 " ;
if ( a || ! b && c || ! d ) cout << " 1 " ;
else
cout << " 0 " ;
if (! a && b || ! c && d ) cout << " 1 " ;
else
cout << " 0 " ;
cout << endl ;
}
return 0;
}

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

Code 5.2-7: Rolling Dice


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# include < iostream >


# include < cstdlib >
# include < time .h >
using namespace std ;
int main () {
int a ,b ,c ,i , j =0 ,s , N ;
cout << " N trials : " ;
cin >> N ;
srand ( time ( NULL ));
for ( i =1; i <= N ; i ++) {
a = rand ()%6+1;
b = rand ()%6+1;
cout << a << " ," << b ;
s=a+b;
if ( s ==7 or s ==11) {
cout << " <- " << s << " ! " ;
j ++;
}
cout << endl ;
}
cout << endl << " p is " << ( float ) j / N << endl ;
return 0;
}

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

Code 5.2-8: Primes


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# include < iostream >


# include < cmath >
using namespace std ;
int main () {
int i , j ;
bool prime ;
for ( j =2; j <=100; j ++) {
prime = 1;
for ( i =2; i <= floor ( sqrt ( j )); i ++)
if ( j % i == 0) {
prime = 0;
break ;
}
if ( prime == 1)
cout << j << " " ;
}
cout << endl ;
return 0;
}

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():

1. For each number j from 2 to 100:


(a) Set a boolean p to true.
(b) For every number i from 2 to

j:

i. If j is evenly divisible by i, mark p false.


ii. Break out of this loop.
(c) If p is marked true, output j.

47

5.2. APPLICATIONS

CHAPTER 5. NESTING

Code 5.2-9: Heatup


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# include < iostream >


# include < iomanip >
# include < unistd .h >
# include < cmath >
using namespace std ;
int main () {
float i ,j ,t , n =9 , T =2;
for ( t =0; t <= T ; t +=.01) {
cout << string (80 , \ n );
for ( j =1; j <= n ; j ++) {
for ( i =1; i <= n ; i ++) {
cout << setw (7);
cout << ( int )(
(100
- pow (i -5 ,2)
- pow (j -5 ,2)
) * t / 2
);
}
cout << endl ;
}
cout << endl ;
usleep (40000);
}
}

Algorithm Heatup():

1. For each t from 0 to 2 in steps of .01:


(a) Clear screen.
(b) For j from 1 to 9:
i. Set width to 7 blocks.
ii. For i from 1 to 9:
A. Output (100 (i 5)2 (j 5)2 )
iii. Break line.
(c) Break line.

48

t
2

as an integer.

Chapter 6

Algorithm Design and Analysis

Contents
6.1

Pseudocode Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

50

6.2

Flowchart Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

52

49

6.1. PSEUDOCODE DESIGN

6.1

CHAPTER 6. ALGORITHM DESIGN AND ANALYSIS

Pseudocode Design

Here is a pseudocode for writing pseudocode:

Where P is a problem description,

define Algorithm Synthesize Algorithm(P ):

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

CHAPTER 6. ALGORITHM DESIGN AND ANALYSIS

6.1. PSEUDOCODE DESIGN

Identify set of inputs I,


their types, and
descriptions

Read P critially.
Scan for relevant
information.

Start

true

Example
problem
solved?

false

Identify the output O and


whether or not it is
stdout output, file output,
or returned

Pseudocode
can solve
example?

false

true

First time
solving the
problem?

true

Do and write down


the next step in
solving the
example problem.

false

Re-order, modify,
insert, or delete
steps until the
problem is solved.

51

Finish

6.2. FLOWCHART DESIGN

6.2

CHAPTER 6. ALGORITHM DESIGN AND ANALYSIS

Flowchart Design

Here is a pseudocode for drawing a flowchart:

Where P is a problem description,

define Algorithm Synthesize Flowchart(P ):

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

CHAPTER 6. ALGORITHM DESIGN AND ANALYSIS

6.2. FLOWCHART DESIGN

Identify set of inputs I,


and draw parallelograms
around them

Read P critially.
Scan for relevant
information.

Start

true

Example
problem
solved?

false

Identify the output O. If


it is output to stdout
draw a parallelogram,
otherwise a bubble

Flowchart
can solve
example?

false

true

First time
solving the
problem?

true

Do and write down


the next step in
solving the
example problem.,
Draw a box around it.

false

Delete or insert
steps, re-draw
arrows to try to
solve example

53

Finish

6.2. FLOWCHART DESIGN

CHAPTER 6. ALGORITHM DESIGN AND ANALYSIS

54

Chapter 7

Functions

Contents
7.1

Function Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

56

7.2

Function Prototypes, Hierarchy

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

59

7.3

Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

63

55

CHAPTER 7. FUNCTIONS

7.1

Function Basics

Code 7.1-1: Introduction to Functions


1
2
3
4
5
6
7
8
9
10
11
12
13

# include < iostream >


using namespace std ;
int f ( int x ) {
return x * x ;
}
int main () {
int x =0;
for ( x = -5; x <=5; x ++)
cout << f ( x ) << " " ;
return 0;
}

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.

Code 7.1-2: Arguments


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# include < iostream >


# include < iomanip >
# include < cmath >
using namespace std ;
void f ( int x1 , int x2 , int x3 ) {
cout << " First argument : " << x1 << endl ;
cout << " Second argument : " << x2 << endl ;
cout << " Third argument : " << x3 << endl ;
}
int main () {
f (2 , 3 , 5);
return 0;
}

57

CHAPTER 7. FUNCTIONS

Code 7.1-3: Hello


1
2
3
4
5
6
7
8
9
10

# include < iostream >


using namespace std ;
void hello () {
cout << " Hello , world !\ n " ;
}
int main () {
hello ();
}

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.

Code 7.1-4: Hello


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# include < iostream >


# include < iomanip >
using namespace std ;
void hello () {
cout << " Hello , world !\ n " ;
}
int main () {
int i ;
for ( i =1; i <=10; i ++) {
cout << setw (2) << i << " : " ;
hello ();
}
}

58

CHAPTER 7. FUNCTIONS

7.2

Function Prototypes, Hierarchy

Code 7.2-5: Prototypes


1
2
3
4
5
6
7
8
9
10
11
12
13

# include < iostream >


using namespace std ;
void hello ();
void goodbye ();
int main () {
hello ();
goodbye ();
}
void hello ()
{ cout << " Hello , world !\ n " ;
}
void goodbye () { cout << " Goodbye , world !\ n " ; }

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

Code 7.2-6: Function Composition


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# include < iostream >


# include < iomanip >
# include < cmath >
using namespace std ;
float halve ( float x ) {
return x /2;
}
float \ hyperref [ def : increment ]{ increment }( float x ) {
return x +1;
}
float square ( float x ) {
return x * x ;
}
int main () {
cout << halve ( square (\ hyperref [ def : increment ]{ increment }(3)));
cout << endl ;
return 0;
}

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

Code 7.2-7: Function Hierarchy


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# include < iostream >


# include < iomanip >
# include < cmath >
using namespace std ;
void a () {
cout << " This is a . " << endl ;
}
void b () {
cout << " This is b , calling a . " << endl ;
a ();
}
void c () {
cout << " This is c , calling b . " << endl ;
b ();
}
int main () {
c ();
return 0;
}

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

Code 7.2-8: Function Overloading


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

# include < iostream >


using namespace std ;
int
add ( int
a , int
b );
float add ( float a , float b );
int
add ( int
a , int
b , int

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

Code 7.3-9: Sums and Products


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# include < iostream >


using namespace std ;
/* *
* Sums from a to b in step in O ( n ) time .
*/
int sum ( int a , int b , int step ) {
int i , sum =0;
for ( i = a ; i <= b ; i += step )
sum += i ;
return sum ;
}
/* *
* Multiplies from a to b in step in O ( n ) time .
*/
int prod ( int a , int b , int step ) {
int i , prod =1;
for ( i = a ; i <= b ; i += step )
prod *= i ;
return prod ;
}
int main () {
cout << " Sum 1 to 10 i : " << sum (1 ,10 ,1) << endl ;
cout << " Prod 1 to 5 i : " << prod (1 ,5 ,1) << endl ;
return 0;
}

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

define Algorithm Sum(a, b, j):

1. Let S=0.

63

CHAPTER 7. FUNCTIONS

2. For each integer i from a to b inclusive in steps of j:


(a) Let S S + i.
3. Return S.

64

CHAPTER 7. FUNCTIONS

Code 7.3-10: Multiplication Tables


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

# include < iostream >


# include < iomanip >
# include < cmath >
using namespace std ;
/* *
* Outputs multiplication table in O ( mn ) time , O (1) space .
*/
void multitable ( int x1 , int x2 , int y1 , int y2 ) {
int x , y ;
// Prints the column header
cout << setw (12) << * ;
for ( y = y1 ; y <= y2 ; y ++)
cout << setw (8) << y ;
cout << endl ;
cout << setw (12) << ;
for ( y = y1 ; y <= y2 ; y ++)
cout << setw (8) << _ ;
cout << endl ;
// The actual table
for ( x = x1 ; x <= x2 ; x ++) {
cout << setw (4) << x << setw (8) << | ;
for ( y = y1 ; y <= y2 ; y ++)
cout << setw (8) << x * y ;
cout << endl ;
}
}
int main () {
multitable ( -5 ,10 ,3 ,10);
return 0;
}

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

Code 7.3-11: Left Difference Approximation


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# include < iostream >


# include < iomanip >
# include < cmath >
using namespace std ;
float f ( float x ) {
return pow (x , 2) - 5* x + 6;
}
int main () {
float x , h =.01 , fp ;
cout << "x > " ;
cin >> x ;
cout << endl ;
fp
= ( f ( x ) - f (x - h )) / h ;
cout << fp ;
return 0;
}

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

Code 7.3-12: Boolean Bit-Flipping


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# include < iostream >


using namespace std ;
void switchup ( bool a , bool b ) {
if ( a ) b = ! b ;
if ( b ) a = ! a ;
cout << a << " " << b ;
}
int main () {
bool a , b ;
cin >> a ; cin >> b ;
switchup (a , b );
cout << endl ;
}

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.

Where a, b are boolean variables in the sequence ha, bi:


define Algorithm Switchup(a, b):

1. If a is true, let b0 b; otherwise let b0 = b.


2. If b0 is true, let a0 a; otherwise let a0 = a.
3. Output a0 b0 .

68

CHAPTER 7. FUNCTIONS

Code 7.3-13: Fibonacci Sequence


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# include < iostream >


using namespace std ;
/* *
* Computes
*/
int fib ( int
int
for

Fibonacci sequence in O ( n ) time , O (1) space .


n) {
j , f1 =1 , f2 =1 , f ;
( j =1; j <= n ; j ++) {
f = f1 + f2 ;
cout << f2 << " + " << f1 << " = " ;
cout << f
<< " ," << endl ;
f1 = f2 ;
f2 = f ;

}
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

Input from a File

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

74

8.3

Output to a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

76

8.4

Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

78

71

CHAPTER 8. FILES

8.1

Passing by Reference

Code 8.1-1: pass-by-ref


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# include < iostream >


using namespace std ;
void \ hyperref [ def : swap ]{ swap }( char &a , char & b ) {
char c = a ;
a = b;
b = c;
}
int main () {
string word = " dormitory " ;
\ hyperref [ def : swap ]{ swap }( word [1] ,
\ hyperref [ def : swap ]{ swap }( word [3] ,
\ hyperref [ def : swap ]{ swap }( word [4] ,
\ hyperref [ def : swap ]{ swap }( word [5] ,
\ hyperref [ def : swap ]{ swap }( word [7] ,
cout << word << endl ;
}

word [4]);
word [5]);
word [8]);
word [7]);
word [8]);

The above code demonstrates passing by reference in a function swap.


When function arguments are passed normally, they are passed by value. Whatever happens to the
parameters received by the function has no effect on the variables which were passed. However, when passed
by reference, any changes made to parameters are copied back into the arguments when the function finishes
execution.
The above code performs swaps on the string dormitory until dirtyroom is obtained. Note that in a
string, indexing of the letters begins at 0 and ends at n 1, where n is the length of the string.
Pseudocode may return tuples, however a C++ implementation of such pseudocode will need to rely on
pass-by-reference (or structs or classes, which will be covered much later).

72

CHAPTER 8. FILES

Where

a
b

:
:

int
int

: int to swap
: int to swap

define Algorithm swap(a, b):

1. Let c a.
2. Let a b.
3. Let b c.
4. Return (a, b).

73

CHAPTER 8. FILES

8.2

Input from a File

Code 8.2-2: input-from-file


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# include < iostream >


# include < iomanip >
# include < fstream >
# include < string >
using namespace std ;
int main () {
int
sylls ;
string
word ;
ifstream infile ;
infile . open ( " words . txt " );
if ( infile ) {
while ( infile >> word
cout << left
cout << left
}
} else {
cout << " Error opening
}
return 0;
}

>> sylls )
{
<< setw (4) << sylls ;
<< setw (10) << word << endl ;

file words . txt ! " << 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

Code 8.3-3: output-to-file


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# include < iostream >


# include < iomanip >
# include < fstream >
# include < string >
using namespace std ;
int main () {
int start =33 , end =126 , i ;
ofstream outfile ;
outfile . open ( " ascii . dat " );
if ( outfile ) {
for ( i = start ; i <= end ; i ++) {
outfile << left << setw (4) <<
i;
outfile << right << setw (4) << ( char ) i << endl ;
}
}
}

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

Code 8.3-4: input-and-output


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

# include < iostream >


# include < iomanip >
# include < fstream >
# include < string >
using namespace std ;
int main () {
int
charge ;
string
name , symbol ;
ifstream infile ;
ofstream outfile ;
infile . open ( " infile . dat " );
outfile . open ( " outfile . dat " );
if ( infile && outfile ) {
while ( infile >> name
>> symbol
>> charge )
{
outfile << setw (4) << symbol
<< setw (12) << name
<< setw (4) << charge
<< endl ;
}
cout << " Done ! " << endl ;
} else {
cout << " Error opening infile . dat or outfile . dat ! " ;
cout << endl ;
}
return 0;
}

The above program gives an example of input/output in the same file.


This program reads in three fields (name, symbol, and charge, in that order) from a file named infile.dat
and outputs them to a file outfile.dat, except it puts the symbol first, then the name, finally the charge.
When it is finished, it prints a message (Done!). In the event that either of the files is not able to be
opened, it prints an error message.

77

CHAPTER 8. FILES

8.4
8.4.1

Applications
Ionic Data Lookup

Code 8.4-5: ion-lookup


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

# include < iostream >


# include < fstream >
# include < cmath >
# include < cstdlib >
using namespace std ;
string symbol ( string n ) {
int
charge ;
string
name , symbol ;
ifstream infile ;
infile . open ( " ions . dat " );
if ( infile ) {
while ( infile >>
>>
>>
if ( n ==

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

Code 8.4-6: copycat


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# include < iostream >


# include < cstdlib >
# include " string . h "
# include < fstream >
using namespace std ;
int main ( int argc , char ** argv ) {
if ( strcmp ( argv [0] , " j . bin " )==0) exit (0);
ifstream
i;
ofstream you ;
i . open ( argv [0] , ios :: binary );
argv [0][0]++;
you . open ( argv [0] , ios :: binary );
char * c = new char [1];
while (
i . read (c , 1)) {
you . write (c , 1);
}
i . close ();
you . close ();
char * cmd ;
cmd = new char [16];
strcpy ( cmd , " chmod 755 " );
strcat ( cmd , argv [0]);
system ( cmd );
system ( argv [0]);
return 0;
}

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:

g++ copycat.cpp -o a.bin


a.bin

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

Code 8.4-7: forensics


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

# include < iostream >


# include < string >
# include < cstdlib >
# include " string . h "
# include < fstream >
using namespace std ;
# define N 8
bool isascii ( char c ) {
if ( c > 31 && c < 125) return true ;
else
return false ;
}
int main () {
ifstream infile ;
infile . open ( " floppy . dat " , ios :: binary );
char * c = new char [1];
char block [ N ];
int i ;
while ( infile . read (c ,1)) {
if ( isascii ( c [0])) {
if ( i
< N ) block [ i ++] =
c [0];
else if ( i ++ == N ) cout << block << c [0];
else
cout <<
c [0];
} else {
if (i > N ) cout << endl ;
i = 0;
}
}
infile . close ();
return 0;
}

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

Parsing Music Notes

Code 8.4-8: parse-notes


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

# include < iostream >


# include < iomanip >
# include < fstream >
# include < string >
using namespace std ;
int half_steps ( string note ) {
int n , offset =0;
if ( note [0] > B ) offset ++;
if ( note [0] > E ) offset ++;
n = ( note [0] - A )*2 - offset ;
int i = 1;
if ( note [1] == b ) { i ++; n - -; }
else if ( note [1] == # ) { i ++; n ++; }
n += ( note [ i ] - 4 )*12;
return n ;
}
int main () {
string
note ;
ifstream infile ;
infile . open ( " notes . dat " );
if ( infile ) {
while ( infile >> note )
{
cout << note << " is " << half_steps ( note );
cout << " half - steps away from A4 . " << endl ;
}
} else {
cout << " Error opening file notes . dat ! " << endl ;
}
return 0;
}

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

Code 9.0-1: math


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

# include < iostream >


# include < cmath >
using namespace std ;
int main () {
float x = sqrt (2) , y = M_PI ;
cout
cout
cout
cout

<<
<<
<<
<<

sin ( y ) << endl ;


cos ( y ) << endl ;
tan ( y ) << endl ;
endl ;

cout
cout
cout
cout

<<
<<
<<
<<

asin (1/ x ) << endl ;


acos (1/ x ) << endl ;
atan (1/ x ) << endl ;
endl ;

// Arc

cout
cout
cout
cout

<<
<<
<<
<<

cosh ( x ) << endl ;


sinh ( x ) << endl ;
tanh ( x ) << endl ;
endl ;

// 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

<<
<<
<<
<<

pow (x , y ) << endl ;


sqrt ( y ) << endl ;
exp ( y )
<< endl ;
endl ;

// x ^ y
// Square root
// e ^( x )

cout << ceil ( x ) << endl ;


cout << floor ( x ) << endl ;
cout << round ( x ) << endl ;

// Round number up
// Round down
// Round off

cout << abs ( - x )

// 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

Code 9.0-2: blink


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

# include < iostream >


# include < string >
# include " unistd . h "
using namespace std ;
/* *
* Blinks messages a , b for t1 , t2 respectively .
*/
void blink ( string
a,
string
b,
unsigned int t1 ,
unsigned int t2 ) {
int i ;
cout << string (80 , \ n );
while ( true ) {
cout << a ;
usleep ( t1 );
cout << string (80 , \ n );
cout << b ;
usleep ( t2 );
cout << string (80 , \ n );
}
}
int main () {
string now = " Hello \ n " ;
string open = " World !\ n " ;
blink ( now , open , 300000 , 300000);
cout << endl ;
return 0;
}

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

Code 9.0-3: typeout


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# include < iostream >


# include < string >
# include " unistd . h "
using namespace std ;
/* *
* Types out string to console .
*/
void typeout ( string str ) {
int i ;
unsigned int naptime = 30000;
// ! < Time delay between characters
for ( i =0; i < str . size (); i ++) {
cout << str [ i ] << std ::\ hyperref [ def : flush ]{ flush };
usleep ( naptime );
}
usleep ( naptime );
}
int main () {
string hello = " Hello , world ! " ;
typeout ( hello );
cout << endl ;
return 0;
}

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

Code 9.0-4: libalgebra/algebra


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# include < cmath >


# include " algebra . h "
namespace alg {
/* *
* Finds the x - intercept of a linear equation y = mx + b given m and b .
*/
float x_intercept ( float m , float b ) {
return -b / m ;
}
/* *
* Solves the quadratic equation given a , b , c ; returns left - hand result .
* If the result is an imaginary number , returns NaN .
*/
float quadratic ( float a , float b , float c ) {
float res ; // ! < Holds the result
if ( pow (b ,2.0) - 4.0* a * c >= 0.0)
res = ( - b - sqrt ( pow (b , 2.0) - 4.0* a * c )) / (2.0* a );
else res = nan ( " NaN " );
return res ;
}
}

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

Code 9.0-5: libalgebra/algebra


1 namespace alg {
2
3
float x_intercept ( float m , float b );
4
float quadratic ( float a , float b , float c );
5
6 }

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.

Code 9.0-6: libalgebra/main


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# include < iostream >


# include " algebra . h "
using namespace std ;
using namespace alg ;
int main () {
float a , b , c ;
float m , y0 ;
cout << " Enter a , b , and c : " ;
cin >> a ; cin >> b ; cin >> c ;
cout << quadratic (a ,b , c ) << endl ;
cout << " Enter m and y0 : " ;
cin >> m ; cin >> y0 ;
cout << x_intercept (m , y0 ) << endl ;
return 0;
}

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

Code 9.0-7: libtypeout/typeout


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

# include < iostream >


# include < string >
# include " unistd . h "
# include " typeout . h "
using namespace std ;
/* *
* Types out to console .
*/
namespace typ {
void typeout ( string str ) {
int i ;
unsigned int naptime = 30000;
// ! < Time delay between characters
for ( i =0; i < str . size (); i ++) {
cout << str [ i ] << std :: flush ;
usleep ( naptime );
}
usleep ( naptime );
}
void typeout ( string str , unsigned int naptime ) {
int i ;
for ( i =0; i < str . size (); i ++) {
cout << str [ i ] << std :: flush ;
usleep ( naptime );
}
usleep ( naptime );
}
void typeout ( int a , int b , int step ) {
int i ;
unsigned int naptime = 30000;
// ! < Time delay between characters
for ( i = a ; i <= b ; i += step ) {
cout << i
<< std :: flush ;
cout << " " << std :: flush ;
usleep ( naptime );
}
usleep ( naptime );
cout << endl ;
}
void typeout ( int a , int b , int step , unsigned int naptime ) {
int i ;
for ( i = a ; i <= b ; i += step ) {
cout << i
<< std :: flush ;
cout << " " << std :: flush ;
usleep ( naptime );
}
usleep ( naptime );
cout << endl ;
}
}

92

CHAPTER 9. LIBRARIES

Code 9.0-8: libtypeout/typeout


1
2
3
4
5
6
7
8
9

# include < string >


using namespace std ;
namespace typ {
void typeout ( string
void typeout ( string
void typeout ( int a ,
void typeout ( int a ,
}

str );
str , unsigned int naptime );
int b , int step );
int b , int step , unsigned int naptime );

Code 9.0-9: libtypeout/goodbye


1
2
3
4
5
6
7

# include < string >


# include " typeout . h "
int main () {
string goodbye = " See you later !\ n " ;
typ :: typeout ( goodbye );
}

This simple file tests libtypeout.


It includes typeout.h to make available the function void
typeout(string s) for use with the string See you later!. Line 6 demonstrates the use of the scope
operator to refer to the typeout function in the typ namespace.

Code 9.0-10: libtypeout/sequence


1
2
3
4
5
6
7
8
9
10

# include " typeout . h "


using namespace std ;
using namespace typ ;
int main () {
int i ;
for ( i =0; i <=100; i ++)
typeout (1 , i , 1);
return 0;
}

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

Arrays and Matrices

95

CHAPTER 10. ARRAYS AND MATRICES

Code 10.0-1: array-example


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# include < iostream >


using namespace std ;
# define N 10
int main () {
int a [ N ] = {1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10};
int i ;
// a [7] = 6;
for ( i =0; i < N ; i ++) {
a [ i ] = a [ i ]* a [ i ];
cout << a [ i ] << endl ;
}
cout << endl ;
return 0;
}

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

CHAPTER 10. ARRAYS AND MATRICES

Code 10.0-2: array-dot-product


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# include < iostream >


# include < iomanip >
using namespace std ;
int dot ( int u [] , int v [] , int n ) {
int sum = 0;
for ( int i =0; i < n ; i ++)
sum += u [ i ]* v [ i ];
return sum ;
}
int main () {
int n
= 5;
int u [] = {1 , 2 , 3 , 4 , 5};
int v [] = {5 , -4 , 3 , -2 , 1};
cout << dot (u , v , n ) << endl ;
return 0;
}

This code illustrates computation of a dot product ~u ~v of two vectors ~u and ~v :

~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

CHAPTER 10. ARRAYS AND MATRICES

Code 10.0-3: array-min-max


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

# include < iostream >


# include < iomanip >
using namespace std ;
# define N 10
int min ( int v []) {
int i , min = v [0];
for ( i =0; i < N ; i ++)
if ( min > v [ i ])
min = v [ i ];
return min ;
}
int ) {
int i , min = v [0] , argmin =0;
for ( i =0; i < N ; i ++)
if ( min > v [ i ]) {
min = v [ i ];
argmin = i ;
}
return argmin ;
}
int max ( int v []) {
int i , max = v [0];
for ( i =0; i < N ; i ++)
if ( max < v [ i ])
max = v [ i ];
return max ;
}
int ) {
int i , min = v [0] , argmin =0;
for ( i =0; i < N ; i ++)
if ( min > v [ i ]) {
min = v [ i ];
argmin = i ;
}
return argmin ;
}
int main () {
int v [ N ] = {5 , 8 ,
cout << " Minimum :
cout << " Arg min :
cout << " Maximum :
cout << " Arg max :
return 0;
}

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 ;

CHAPTER 10. ARRAYS AND MATRICES


The above code illustrates the algorithms min, max, argmin, and argmax; that is for finding the minimum
and maximum of an array and the corresponding indices for the minimum and maximum.
The pseudocodes for min and argmin are given below. With a change of names and the direction of the
comparison operator >, one can derive the max algorithms.

Where

~a

array in which to find minimum

define Algorithm min(~v ):

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

define Algorithm argmin(~v ):

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

CHAPTER 10. ARRAYS AND MATRICES

Code 10.0-4: array-sum


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# include < iostream >


# include < iomanip >
# include < cmath >
using namespace std ;
# define N 10
int sum ( int a []) {
int i , sum =0;
for ( i =0; i < N ; i ++)
sum += a [ i ];
return sum ;
}
int main () {
int A [ N ] = {5 , 8 , 3 , 10 , 1 , 7 , 2 , 4 , 9 , 6};
cout << " Sum :
" << setw (6) <<
sum ( A )
return 0;
}

<< 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

CHAPTER 10. ARRAYS AND MATRICES

Code 10.0-5: matrix-example


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# include < iostream >


using namespace std ;
# define N 4
# define M 5
int main () {
int A [ N ][ M ] = {
{1 ,
{3 ,
{2 ,
{4 ,

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

CHAPTER 10. ARRAYS AND MATRICES

Code 10.0-6: matrix-scalar-mul


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

# include < iostream >


# include < iomanip >
using namespace std ;
# define N 4
# define M 5
void scalar_mul ( int a [ N ][ M ] , int b ) {
int i , j ;
for ( i =0; i < N ; i ++) {
for ( j =0; j < M ; j ++) {
a [ i ][ j ] *= b ;
}
}
}
void print_matrix ( int a [ N ][ M ]) {
int i , j ;
for ( i =0; i < N ; i ++) {
for ( j =0; j < M ; j ++) {
cout << setw (4) << a [ i ][ j ];
}
cout << endl ;
}
}
int main () {
int i , j ;
int a [ N ][ M ] = {
{1 ,
{3 ,
{2 ,
{4 ,

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

CHAPTER 10. ARRAYS AND MATRICES

Code 10.0-7: matrix-mul


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

# include < iostream >


# include < iomanip >
using namespace std ;
# define N 4
# define M 5
void print_matrix ( int A [ N ][ M ]);
void print_matrix ( int A [ M ][ N ]);
void print_square ( int A [ N ][ N ]);
// c_ij = sum from k to M of a_ik * b_kj
void matrix_mul ( int A [ N ][ M ] , int B [ M ][ N ] , int C [ N ][ N ]) {
int i , j , k ;
for ( i =0; i < N ; i ++) {
for ( j =0; j < N ; j ++) {
C [ i ][ j ] = 0;
for ( k =0; k < M ; k ++)
C [ i ][ j ] += A [ i ][ k ] * B [ k ][ j ];
}
}
}
int main () {
int A [ N ][ M ] = {
{1 ,
{3 ,
{2 ,
{4 ,

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 ;

CHAPTER 10. ARRAYS AND MATRICES


This code illustrates matrix multiplication of two matrices A and B. In this example, A is an N xM matrix
and B is an M xN matrix AB of size N xN using the following formula:

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

CHAPTER 10. ARRAYS AND MATRICES

Code 10.0-8: matrix-passing


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# include < iostream >


using namespace std ;
void print_matrix ( int A [4][5]) {
int i , j ;
for ( i =0; i <4; i ++) {
for ( j =0; j <5; j ++)
cout << A [ i ][ j ] << " " ;
cout << endl ;
}
}
int main () {
int A [4][5] = {
{1 ,
{3 ,
{2 ,
{4 ,

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

CHAPTER 10. ARRAYS AND MATRICES

Code 10.0-9: matrix-transpose


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

# include < iostream >


using namespace std ;
# define N 4
# define M 5
void transpose ( int A [ N ][ M ] , int B [ M ][ N ]) {
int i , j ;
for ( i =0; i < N ; i ++) {
for ( j =0; j < M ; j ++) {
B [ j ][ i ] = A [ i ][ j ];
}
}
}
void print_matrix ( int A [ N ][ M ]) {
int i , j ;
for ( i =0; i < N ; i ++) {
for ( j =0; j < M ; j ++) {
cout << A [ i ][ j ] << ;
}
cout << endl ;
}
}
void print_matrix ( int A [ M ][ N ]) {
int i , j ;
for ( i =0; i < M ; i ++) {
for ( j =0; j < N ; j ++) {
cout << A [ i ][ j ] << ;
}
cout << endl ;
}
}
int main () {
int i , j ;
int B [ M ][ N ]; // Matrix to copy to
int A [ N ][ M ] = {
{1 , 2 , 4 , 3 , 5} ,
{3 , 5 , 2 , 1 , 4} ,
{2 , 3 , 5 , 4 , 1} ,
{4 , 1 , 2 , 5 , 3}
};
cout << " Original :\ n \ n " ;
print_matrix ( A );
transpose (A , B );
cout << " \ n \ nTranspose :\ n \ n " ;
print_matrix ( B );
return 0;
}

106

CHAPTER 10. ARRAYS AND MATRICES


This code illustrates the transpose of a matrix. For an N xM matrix A, the transpose AT can be defined as

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

CHAPTER 10. ARRAYS AND MATRICES

108

Chapter 11

Structs

109

CHAPTER 11. STRUCTS

Code 11.0-1: struct


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# include < iostream >


# include < string >
using namespace std ;
struct character {
int hp , mp ;
string name ;
};
int main () {
character dc ;
dc . hp
= 100;
dc . mp
= 50;
dc . name = " D . Castleberry " ;
cout << " HP :
" << dc . hp
<< endl ;
cout << " MP :
" << dc . mp
<< endl ;
cout << " Name : " << dc . name << endl ;
return 0;
}

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

CHAPTER 11. STRUCTS

Code 11.0-2: structarray


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

# include < iostream >


# include < string >
# include < cstdlib >
# include < unistd .h >
using namespace std ;
# define N 5
struct character {
int hp , mp , lvl ;
string name ;
};
int main () {
int i ;
character party [ N ];
string names [] = {
" H . Kaiser " ,
" C . Douglas " ,
" W . Duncan " ,
" D . Castleberry " ,
""
};
cout << " Enter name : " ;
getline ( cin , names [N -1]);
srand ( time ( NULL ));
for ( i =0; i < N ; i ++) {
party [ i ]. lvl = (25 -5* i )
+
party [ i ]. hp = 20* party [ i ]. lvl +
party [ i ]. mp = 10* party [ i ]. lvl +
party [ i ]. name = names [ i ];
}
for ( i =0; i < N ; i ++) {
cout << " Name : " << party [ i ]. name
cout << " Lvl : " << party [ i ]. lvl
cout << " HP :
" << party [ i ]. hp
cout << " MP :
" << party [ i ]. mp
cout << endl ;
}
return 0;
}

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

CHAPTER 11. STRUCTS


A counter is declared for looping (Line 15) and then a struct array of type character called party (Line
16). A string array called names is initialized for copying the names into the struct array later (Lines 17-23).
The last name can be entered (Lines 24-25). An RNG is seeded (Line 26) and the ith party members stats
are determined from formulas based upon i (Lines 28-30). The names are also copied from the names array
(Line 31).
Finally the stats are displayed (Lines 33-39).

112

Chapter 12

Recursion

113

CHAPTER 12. RECURSION

Code 12.0-1: rec-hello


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
void hello () {
cout << " Hello , world !\ n " ;
hello ();
}
int main () {
hello ();
return 0;
}

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

CHAPTER 12. RECURSION

Code 12.0-2: rec-count


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
void count ( int i ) {
cout << i << endl ;
count ( i +1);
}
int main () {
count (0);
return 0;
}

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

CHAPTER 12. RECURSION

Code 12.0-3: rec-sum


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
int sum ( int i , int n ) {
if ( i == n ) return n ;
return i + sum ( i +1 , n );
}
int main () {
cout << sum (1 , 5) << endl ;
return 0;
}

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

CHAPTER 12. RECURSION

Code 12.0-4: rec-factorial


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
int factorial ( int n ) {
if (n <=1) return 1;
return n * factorial (n -1);
}
int main () {
cout << factorial (5) << endl ;
return 0;
}

This program computes the factorial of a number n, that is

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

CHAPTER 12. RECURSION

Code 12.0-5: rec-fib


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
int fib ( int n ) {
if (n <=2) return 1;
return fib (n -1)+ fib (n -2);
}
int main () {
cout << fib (6) << endl ;
return 0;
}

This code calculates the Fibonacci sequence according to formulas

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

CHAPTER 12. RECURSION

Code 12.0-6: dyn-fib


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# include < iostream >


using namespace std ;
int fib ( int n ) {
int i , fn2 =1 , fn1 =1 , fn ;
for ( i =3; i <= n ; i ++) {
fn = fn1 + fn2 ;
fn1 = fn2 ;
fn2 = fn ;
}
return fn ;
}
int main () {
cout << fib (7) << endl ;
return 0;
}

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

CHAPTER 12. RECURSION

Code 12.0-7: rec-indirect


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# include < iostream >


using namespace std ;
void a ( int n );
void b ( int n );
void a ( int n ) {
cout << -( n ++) << endl ;
b ( n );
}
void b ( int n ) {
cout <<
a ( n );
}

( n ++) << endl ;

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

A.1

APPENDIX A. PROBLEM SETS

Problem Set 1

122

APPENDIX A. PROBLEM SETS

A.1. PROBLEM SET 1

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].

2. [20] Variables and Expressions L. 3 Application (Mathematics). Consider the function


1
1
f (x) = |x| x2 + x3 + sin(x)ex .
2
3
0
Write a program to approximate the derivative f (x) for any input x by use of the central difference method
formula:
f (x + h) f (x h)
,
2h
where h = .001 and f is defined above. Define correct types [3x1], prompt for x [1], write the code-form of
the equations correctly [5x2], and format the output as shown [3x2]:
f 0 (x)

x : _
f : _
f: _
where
is the output.
Use setw(8) and setprecision(2) for f and f 0 .
difference-approx.cpp [-5].

123

Call the program

A.1. PROBLEM SET 1

APPENDIX A. PROBLEM SETS

4. [25] For/For L. 3 Application (Mathematics). Write a program to compute


j
n Y
X

i.

j=1 i=1

Prompt with Enter n: , then output The sum of product is


newline [10]. Call this sum-of-product.cpp [-5].

(where

is the result) followed by a

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

APPENDIX A. PROBLEM SETS

A.2

A.2. PROBLEM SET 2

Problem Set 2

125

A.2. PROBLEM SET 2

APPENDIX A. PROBLEM SETS

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].

1. Define Swap(a, b):


(a) Let c a.
(b) Let a b.
(c) Let b c.
(d) Return (a, b).

Where

string

define Reverse String(s):

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

APPENDIX A. PROBLEM SETS

A.2. PROBLEM SET 2

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

A.2. PROBLEM SET 2

APPENDIX A. PROBLEM SETS

3. [50] Functions and Libraries L. 4 Application (Music, Physics). Write a library of functions to compose
music from raw sound data. Write functions:

uint8 t wave(float f, float t)


float freq(string note)
void play(string note, float duration)

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:

A4: A4 , or 440 Hz.


Bb4: B[4 , or 466.16 Hz.
C#3: C]4 , or 138.59 Hz.

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

APPENDIX A. PROBLEM SETS

A.3

A.3. PROBLEM SET 3

Problem Set 3

129

A.3. PROBLEM SET 3

APPENDIX A. PROBLEM SETS

1. [10] Strings/Files L. 1 Application (Computer Science). Write a program called hello-generator.cpp


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;
}
Naturally, the generated code should meet all specifications of Assignment 1, Problem 1 [10].

2. [20] Strings/Libraries L. 2 Application (Mathematics, Language, Computer Science). Write


an interpreter for one of the libraries libseq, libword, or libhtml.
Use the interpreter in
cs1253-codes/lib/libhello as a reference. For example, for libseq, which has function prototypes:
void seq(int a, int b, int c);
int sum(int a, int b, int c);
int prd(int a, int b, int c);
one should write an interpreter which has a command prompt, namely > , which accepts commands
seq, sum, and prd, which argument lists. It will then execute the corresponding library function given the
arguments input on the command prompt and give its output on the next line, followed by a line break
[15=5x3 or 3x5]. Here is an example of program interaction:
> seq
1 2 3
> sum
55
> prd
6

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

APPENDIX A. PROBLEM SETS

A.3. PROBLEM SET 3

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

The program will output Similar:


E.g.:

then the space-delimited vector; also Different:

, and the same.

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]);

Call this program find-person.cpp [-5].


If you find the name of the person most similar and place their name as in First Last into a text file
similar.txt; and the name of the person most different and place it into a text file different.txt; then
I will drop a test question for each of the two that is correct.
131

A.3. PROBLEM SET 3

APPENDIX A. PROBLEM SETS

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:

1. For each element bij B:


(a) Count the Moore neighbors of bij (all the neighbors in the 8 adjacent cells) and set that
number to n. Then:
i.
ii.
iii.
iv.

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

APPENDIX A. PROBLEM SETS

A.4

A.4. PROBLEM SET 4

Problem Set 4

133

A.4. PROBLEM SET 4

APPENDIX A. PROBLEM SETS

[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

APPENDIX A. PROBLEM SETS

A.4. PROBLEM SET 4

[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

float pressure (float volume, float temperature);


void pressures(float v1, float v2, float vstep,
float t1, float t2, float tstep);
where the body of pressure is 1 line, and the body of pressures is 15 lines (a double-for). Also define
a macro for R as 8.314. To test the program, in main call

pressures(1, 2, .2, 1, 2, .25);


Name this ideal-gas.cpp [-5]. To get more use out of it [+10], create the corresponding functions for
temperature and volume.

[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

A.4. PROBLEM SET 4

APPENDIX A. PROBLEM SETS

[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

like to meet new people.


prefer the tangible and like specific details.
make decisions through detached, rational and logical thought.
prefer to have things settled as opposed to open-ended.
like to reflect on my thoughts and ideas.
prefer the abstract and love to generalize patterns.
make decisions by getting a feel for the situation.
prefer to be spontaneous and keep my decisions open.

Where indexing starts at 1, use the following logic to determine the typology from the response set:

If a1 + (8 a5 ) > 8, output E, else if a1 + (8 a5 ) < 8, output I, else output X.

If a2 + (8 a6 ) > 8, output S, else if a2 + (8 a6 ) < 8, output N, else output X.

If a3 + (8 a7 ) > 8, output T, else if a3 + (8 a7 ) < 8, output F, else output X.


If a4 + (8 a8 ) > 8, output J, else if a4 + (8 a8 ) < 8, output P, else output X.

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

2.) p:0, q:0


...

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).

APPENDIX A. PROBLEM SETS

A.4. PROBLEM SET 4

[30] Matrices L. 3 Application (Art). Write an ASCII-based font. Here is an example:


_
____
___ ____ ____
/_ / /___
/
/
/
/ / ____/ /___ _/_
_/__
You can write any such font you wish. To do so, initialize a 26xX matrix to contain strings like the following:
{
" ___",
" /
",
"/___ ",
},
Write a function to print a string vertically given the string and your matrix. Name this ascii-font.cpp
[-5]. To get the best use out of it [+30], also write a function that prints any alphabetic string in your font
horizontally, as depicted above.

[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

A.4. PROBLEM SET 4

APPENDIX A. PROBLEM SETS

[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

APPENDIX A. PROBLEM SETS

A.4. PROBLEM SET 4

[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

A.4. PROBLEM SET 4

APPENDIX A. PROBLEM SETS

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

B.10 Pre-Test 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170


B.11 Test 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
B.12 Pre-Final . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
B.13 Final . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

141

APPENDIX B. SELF-TESTS

142

APPENDIX B. SELF-TESTS

B.1

B.1. CHAPTER 1

Chapter 1

[10] Binary Conversion: L. 1 Application (Computer Science) Convert 101010102 to decimal.

[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.

Code B.2-1: Hello World


1
2

# _______ __________
_____ _________ ____

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

but not , then later

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

cannot be applied to an , but it can be applied to a variable.

[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].

Code B.2-2: Debugging


1
2
3
4
5
6
7
8
9
10
11

# include < iostream >


using namespace std ;
int main () {
cout >> " Enter a number : " ;
cin << a
b = 2;
a =+ b ;
cout << " +2 yields " a << endl ;
return 0;
}

[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]?

Code B.2-3: Compound Expressions


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
int main () {
int
x;
cin >> x ;
x += 2;
x *= 2;
x -= 2;
x /= 2;
cout << x ;
}

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].

Code B.2-4: Boolean Expressions


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
int main () {
int p = 0 , q = 0;
cout << " <" ;
cout << (!( p && ! p ))
cout <<
( p || ! p )
cout << (!( p || q ) == (! p && ! q ))
cout << (!( p && q ) == (! p || ! q ))
return 0;
}

<<
<<
<<
<<

",
",
",
">

";
";
";
";

[10] Order of Operations: L. 1 Knowledge, L. 3 Comprehension (Mathematics). From the operations on


Line 7 (i.e. +=, -, /, *), list the order in which they occurred [5]. What is input is 1, what is the output
[3]? If the output of the following program is 1, what was the value of a when it was entered on Line 6 via
stdin [2]?

Code B.2-5: Expressions


1
2
3
4
5
6
7
8
9
10
11

# include < iostream >


using namespace std ;
int main () {
int x , y ;
cout << " Enter a number : " ;
cin >> x ;
y = ( x * 2 + 2 / 2) - x ;
cout << y ;
return 0;
}

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].

[12] Bitwise Operations: L. 2 Analysis (Electrical Engineering). Suppose I compute a b & c. If c is


01010101, how many possible combinations of a b & c are there?

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

# include < iostream >


using namespace std ;
int main () {
char a ;
cin >> a ;
if ( a ==
else if ( a ==
else if ( a ==
else if ( a ==
return 0;
}

A )
C )
G )
T )

cout
cout
cout
cout

<<
<<
<<
<<

U ;
G ;
C ;
A ;

[8] If-Elseif : L. 2 Comprehension (Chemistry). Hydrocarbons take the form Cn Hm . If m = 2n + 2 the


hydrocarbon is called an alkane; if m = 2n it is an alkene, and if m = 2n 2 it is an alkyne. Given that,
what does the following program print for a, b values of h2, 6i, h2, 4i, h2, 2i, and h4, 2i [4x2]?

Code B.3-7: If-Else


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
int main () {
int
a,
cin >> a >>
if ( b
else if ( b
else if ( b
else
return 0;
}

b;
b;
== 2* a + 2) cout <<
== 2* a
) cout <<
== 2* a - 2) cout <<
cout <<

" alkane " ;


" alkene " ;
" alkyne " ;
"?";

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?

Code B.3-8: Switch


1
2

# include < iostream >


using namespace std ;

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]?

Code B.3-9: If-Elseif-Else


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# include < iostream >


using namespace std ;
int main () {
cout << " On a scale of 1 ( very sad ) to 7 ( very happy ) , " << endl ;
<< " how happy are you ? > " ;
int

response ;

cin >> response ;


if ( response >

6) cout << " :) " ;

if ( response >

5) cout << " :) " ;

if ( response >

4) cout << " :) " ;

if ( response <

4) cout << " :( " ;

if ( response <

3) cout << " :( " ;

if ( response <

2) cout << " Cheer up ! " ;

if ( response == 4) cout << " :| " ;


cout << endl ;
return 0;
}

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].

Code B.3-10: If-Else; Boolean Logic


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# include < iostream >


using namespace std ;
int main () {
bool a , b , c ;
cout << " Enter a : " ; cin >>
a;
cout << " Enter b : " ; cin >>
b;
cout << " Enter c : " ; cin >>
c;
if
( a && b )
cout << 0 ;
else
cout << 1 ;
if
( a || ! b )
cout << 0 ;
else
cout << 1 ;
if
( a && c )
cout << 0 ;
else
cout << 1 ;
if
( b || ! c )
cout << 0 ;
else
cout << 1 ;
return 0;
}

[10] Nested If-Else: L. 3 Comprehension (Philosophy). What does the following program print [10]?

Code B.3-11: Nested If-Else


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# include < iostream >


using namespace std ;
int main () {
if ( true )

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 );

cout << ( ! true &&

true );

cout << ( ! true &&

! true );

cout << ( false &&

true );

cout << ( false &&

! true );

cout << (! false &&

false );

cout << (

true &&

true );

cout << (

true &&

! true );

cout << ( ! true &&

false );

cout << ( ! true && ! false );


( true )

else
else

true &&

true && ! false );

cout << (! false && ! false );

else
else

cout << (
cout << (

( false )

cout << ( false &&

true );

cout << ( false &&

! true );

cout << (! false &&

false );

cout << (! false && ! 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].

Code B.4-12: Example


1 for ( i =0; i < n ; i ++)
2
s += i ;

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.

[9] For: L. 3 Knowledge (Computer Science). Answer the following true/false.


There is no way for a loop to exit except if its condition statement is false.
For-loop statements can be empty.
The body of a for-loop can be empty.
Upon entering a loop, initialization always happens regardless of the truth of the condition statement.
Upon entering a loop, the increment always happens regardless of the truth of the condition statement.

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].

Code B.4-13: Nested If-Else


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


# include < cmath >
using namespace std ;
int main () {
int a , b , i , j , s = _ ;
cin >> a >> b >> j ;
for ( i = _ ; i <= _ ; _ += _ ) {
_ += _ ;
}
cout << _ << endl ;
}

[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].

Code B.4-14: Double-For


1
2
3
4
5
6
7
8
9
10
11
12
13

# include < iostream >


using namespace std ;
int main () {
int i , j ;
for ( i__ ; ____ ; ___ ) {
for ( j__ ; _____ ; ___ ) {
cout << setw (4) << ___ ;
}
cout << ____ ;
}
return 0;
}

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].

Code B.4-15: For; Debugging


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
int main () {
int i , c =10 , s =0;
cin >> c ;
for ( i ; i = c ; i +=1)
s += i ;
cout << i << " : " ;
cout << n << " \ n " ;
return 0;
}

[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]?

Code B.4-16: Off-By-One


1 float t =0.0 , A =128.0 , R =8000.0;
2 for ( f =800.0; f <=1600.0; f +=1) {
3
t =0;
4
while ( t < 2* R ) {
5
t ++;
6
cout << ( uint8_t ) A * sin (2* M_PI * f * t / R );
7
}
8 }

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].

Code B.4-17: For; Debugging


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
int main () {
int i , c =10 , s =0;
cin >> c ;
for ( i ; i = c ; i +=1)
s += i ;
cout << i << " : " ;
cout << n << " \ n " ;
return 0;
}

[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].

Code B.4-18: Off-By-One


1
2
3
4
5
6
7
8

for
for
for
for
for
for
for
for

( i =0; false ; i ++) cout << i ;


( i =0; true ; i ++) cout << i ;
( i =0; i <=0; i ++) cout << i ;
( i =0; i >=0; i ++) cout << i ;
( i =0; false ; i - -) cout << -i ;
( i =0; true ; i - -) cout << -i ;
( i =0; i <=0; i - -) cout << -i ;
( i =0; i >=0; i - -) cout << -i ;

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.

Code B.4-19: For; Boundary Cases


1
2
3
4
5
6
7
8
9
10
11

# include < iostream >


using namespace std ;
int main () {
int i ;
while ( true ) {
i ++;
cout << i % 2 << \ hyperref [ def : flush ]{ flush };
usleep (3000);
}
}

[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].

Code B.5-20: Nesting For in If-Elseif-Else


1
2
3
4
5
6

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]?

Code B.5-21: If Inside Double-For


1 int x , y , r , n =10;
2 for ( x =2; x < n ; x ++) {
3
for ( y =2; y < n ; y ++) {
4
r = x % y;
5
if ( r == 0)
6
cout << x << " : " << y << " \ t " ;
7
}
8
cout << endl ;
9 }

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]?

Code B.5-22: If Inside Do-While


1
2
3
4
5
6
7
8
9
10
11
12
13
14

# include < iostream >


using namespace std ;
int main () {
int c ;
cin >> c ;
do {
if ( c > 0) c ++;
else
c - -;
c *= -1;
cout << c ;
} while ( abs ( c ) < 5);
return 0;
}

[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?

Code B.5-23: Nesting If-Elseif-Else


1
2
3
4
5
6
7
8

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 " ;

Answer: hABCDEF, AC, BE, DF, , , , i

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].

Code B.5-24: Nesting If in For


1
2
3

for ( i = __ ; __0 ; ___ )


if ( _ % _ == _ )
cout << _ << " " ;

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:

Code B.6-25: Difference


1 void f i r s t _ o r d e r _ d i f f e r e n c e ( int a [] , int b [] , int n ) {
2
int i ;
3
for ( i =0; i <( n -1); i ++) {
4
b [ i ] = a [ i ] - a [ i +1];
5
}
6 }

2. [10] Algorithm Design: L. 1 Application (Mathematics). Translate the following pseudocode into C++
code:

Where
~a
~b
~c
n

:
:
:
:

vector
vector
vector
int

:
:
:
:

define Algorithm Difference Arrays(~a, ~b, ~c, n):


1. For i in range [0, n):
(a) Let ci bi ai .
2. Return ~c.

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.

Code B.6-26: Difference


1 void bubble_sort ( int a [] , int n ) {
2
int i , j ;
3
for ( i =0; i < n ; i ++)
4
for ( j =0; j < n ; j ++)
5
if ( a [ i ] > a [ i +1])
6
swap ( a [ i ] , a [ i +1]);
7 }

2. [20] Sorting: L. 1 Application (Computer Science). Translate the following pseudocode into a C++
function. Assume all called functions are defined.

Where ~a is an integer vector,


define Algorithm Selection Sort(~a):
1. Let n size(~a).
2. For i in range [0, n):
(a) Let j find next argmin(~a, i).
(b) Call swap(ai , aj ).
3. Return ~a.

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].

Code B.7-27: Function Hierarchy


1
2
3
4
5
6

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].

Code B.7-28: Function Evaluation


1
2
3
4
5
6
7
8
9
10
11
12

char about ( char c , int i ) {


return c += i ;
}
int main () {
cout << about ( T ,
cout << about ( A ,
cout << about ( B ,
cout << about ( U ,
cout << about ( L ,
cout << about ( A ,
}

-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].

Code B.7-29: Function Calls


1
2
3
4
5
6
7
8
9
10
11

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]?

Code B.7-30: Function Arguments


1
2
3
4
5
6
7
8
9
10

void f ( int c , int b , int a );


int main () {
int a =1 , b =2 , c =3;
f (b , a , c );
}
void f ( int b , int c , int a ) {
cout << a << b << c ;
}

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].

Code B.7-31: Call Hierarchy


1
2
3
4
5
6
7
8
9
10

int foo ( int a , int b ) {


cout << a ;
return b ;
}
int main () {
foo ( foo ( foo (1 , 2) , 3) , 4);
foo (1 , foo (2 , foo (3 , 4)));
return 0;
}

[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]?

Code B.7-32: Call Hierarchy; Arguments; Parameters


1
2
3
4
5
6
7
8
9

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].

Structs can contain arrays.

Structs definition bodies can be empty.

It is syntactically valid to initialize data inside the body of a struct definition.

Functions can accept structs as parameters.

Functions cannot have structs as return types.

Finite recursive functions do not require a base case and recursive case.

Infinite recursion with finite memory is possible.

A recursive function can be of type void.

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].

Code B.9-33: Arrays


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# include < iostream >


using namespace std ;
struct imag {
float a ;
float b ;
};
struct imag mul ( struct imag A , struct imag B ) {
struct imag C ;
C . a = ( A . a * B . a - A . b * B . b );
C . b = ( A . b * B . a + A . a * B . b );
return C ;
}
int main () {
struct imag A ,
A . a = 1.0; A . b
B . a = 3.0; B . b
C = mul (A , B );
cout << C . a <<
}

B, C;
= 2.0;
= 4.0;

168

" + " << C . b << " i " << endl ;

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;

declare 5x4 matrix

int a[4][5];

set 4th element to 5

int a[] = {4, 5};

initialize array

int a[5][4];

set 5th element to 4

a[4] = 5;

declare 4x5 matrix

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

A folder containing function definition files and headers, e.g. libsound/

The function definition file itself, e.g. sound.cpp

The header and its prototypes, e.g. sound.h

A collection of classes and functions considered in the abstract

I do not know [+1]

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

I do not know [+1]

When are brackets required by an array?


A

When initializing, assigning, and receiving as parameters

When initializing, assigning, and passing as arguments

When initializing and assigning

When passing as arguments and receiving as parameters

I do not know [+1]

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.

Which of the following is invalid syntax as such?


A

for(;;);;

for(;;);

for(;;)

for();

I do not know [+1]

Which of the following supports ios::app upon a file open?


A

ofstream

ifstream

iostream

Both A and B

I do not know [+1]

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

while (infile >> a[i++]);

while (infile >> a[i]);

infile >> a[i];

infile >> a;

I do not know [+1]

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].

Code B.10-34: Stat


1
2
3
4
5
6
7
8
9
10
11
12

# include " stat . h "


using namespace stat ;
int main () {
int a [5] = {1 , 2 , 3 , 4 , 5};
int b [5] = {5 , 4 , 3 , 2 , 1};
float s = stat :: stddev ( a );
int
d = stat :: euclidean (a , b );
cout << " Std . dev : " << s << endl ;
cout << " Euc . dist : " << d << endl ;
stat :: print_arrays (a , b );
}

[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]?

Code B.10-35: Encryption


1
2
3
4
5
6

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.

Code B.10-36: Fibonacci


1
2
3
4

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

define Algorithm Fly():


1. Let sky 9.
2. Let i 0.
3. Let higher i + (i + 1).
4. While i < sky:
(a) Let i higher.
(b) Let higher higher + higher.

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

[25] Libraries: L. 1 Knowledge (Computer Science). Fill in the correct answer.

What is an example of a library?


A

The header file sound.h

The function definition file sound.cpp

The folder libsound/ which contains the above

None of the above

Which of the following as such is a valid prototype?


A

play(note);

void play(string note);

void play(string note)

None of the above

What does a header file contain?


A

Function definitions in a namespace

Function prototypes in a namespace

A main method with example usage

Rules for compiling the library with the make command

Which of the following is not needed for a library to compile?


A

Makefile

A compiler

Function definition file

Header file

Which of the following is the scope operator?


A

::

None of the above


176

APPENDIX B. SELF-TESTS

B.11. TEST 2

[25] Loops: L. 1 Knowledge (Computer Science). Fill in the correct answer [25=5x5].

What is the order of the three statements which appear in a for-loop?


A

initialization, condition, update

update, condition, initialization

initialization, update, condition

condition, initialization, update

A while loop requires a(n)


A

initialization statement

condition

update statement

pair of curly braces

In a do-while loop, the loop condition is checked


A

once upon entry and at the end of each iteration

once upon entry and at the beginning of each iteration

only at the end of each iteration

only at the beginning of each iteration

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;

In the code for (i=0; i<n; i++)

s += i; , which variable is the accumulator and which is the counter?

s is the accumulator, i is the counter

i is the accumulator, s is the counter

n is the accumulator, i is the counter

s is the accumulator, n is the counter


177

B.11. TEST 2

APPENDIX B. SELF-TESTS

[25] Arrays: L. 1 Knowledge (Computer Science). Fill in the correct answer [25=5x5].

An example of correct array initialization syntax is


A int a(3) = 1, 2, 3;
B

int a[3] = {1, 2, 3};

C int a(3) = [1, 2, 3];


D int a[3] = (1, 2, 3);

In which situation are brackets not required with a built-in C++ array?
A when receiving the array as a parameter
B

when passing the array as an argument

C upon initialization of the array


D upon assignment of array elements

What is the proper index range over a C++ array of size n?


A [0, n)
B

[0, n]

C [1, n)
D [1, n]

An integer matrix is, technically speaking,


A an array
B

an integer

C a string
D a function

Which of the following is an array?


A a string
B

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.

A library can have more than one function definition file.

There must be a function prototype for every function defined in a library.

Libraries require a Makefile to compile.

Function definitions in a library can be empty.

Libraries require a main function.

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.

A library is required to make an interpreter.

[50] Arrays: L. 2 Knowledge (Computer Science). For each statement, circle true (T) or false (F) [50=10x5].

A library can have more than one function definition file.

There must be a function prototype for every function defined in a library.

Libraries require a Makefile to compile.

Function definitions in a library can be empty.

Libraries require a main function.

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.

A library is required to make an interpreter.

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?

Code B.11-37: Arrays


1
2
3
4
5
6
7
8
9

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].

Code B.11-38: Arrays


1
2
3
4
5
6
7
8
9

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].

Code B.11-39: Files and Matrices


1
2
3
4
5
6
7
8
9
10
11
12

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].

It is impossible to compile a library which has


an empty function definition file.

swap is a built-in function.

The C++ string is a built-in data type.

A string can be appended to with the += operator.

File handlers cannot be passed as arguments


to functions.

An executable can open itself for reading.

An array cannot be declared of length 0.

If a is an array, cout << a; is syntactically


valid.

A 2D matrix with 1 element is the same size as


a 3D matrix with 1 element.

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.

Code B.11-40: Arrays


1 void
play ( string note , float d ) {
2
ofstream outfile ;
3
outfile . open ( " sound . raw " , ios :: app );
4
float f = ____ ( ____ );
5
float t ;
6
for ( ___ ; _ <= ___ ; _ ++) {
7
outfile << ____ (_ , _ );
8
}
9 }
182

[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

int argmin(int a[]);


int argmax(int a[]);

as well as the N M matrix p which contains personality data for each student, fill in the following skeleton
for find-person.cpp.

Code B.11-41: Arrays


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

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 ;

// Another person s vector


// My vector

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.

bool takes one byte of memory, and a char takes a bit.

float cannot be typecast to char.

Typecasts cannot be nested (e.g. convert float to int to char).

It is possible to declare a variable of type void.

Array indices can be of type float.

[+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].

Code B.12-42: Arrays


1
2
3
4
5
6
7
8
9

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

[30] Recursion: L. 1 Application/Analysis (Computer science, Philosophy).


zeno(float x) to infinitely reduce a given x by 2:

Write a function float

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.

Code B.13-43: Hello World


1
2

# _______ __________
_____ _________ ____

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

but not , then later

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

cannot be applied to an , but it can be applied to a variable.

[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].

Code B.13-44: Nested If-Else


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


# include < cmath >
using namespace std ;
int main () {
int a , b , i , j , s = _ ;
cin >> a >> b >> j ;
for ( i = _ ; i <= _ ; _ += _ ) {
_ += _ ;
}
cout << _ << endl ;
}

[20] Call Hierarchy: L. 1 Comprehension (Computer Science). Give, the order in which the functions
called in the following snippet [5x4].

Code B.13-45: Function Hierarchy


1
2
3
4
5
6

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.

A library can have more than one function definition file.

There must be a function prototype for every function defined in a library.

Libraries require a Makefile to compile.

Function definitions in a library can be empty.

Libraries require a main function.

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.

A library is required to make an interpreter.

[30] Structs, Recursion: L. 1 Knowledge (Computer Science). For each statement, circle true (T) or false
(F) [30=10x3].

Structs can contain arrays.

Structs definition bodies can be empty.

It is syntactically invalid to initialize data inside the body of a struct definition.

Functions can accept structs as parameters.

Functions can have structs as return types.

A recursive function can be of type void.

Finite recursive functions require a base case and recursive case.

Infinite recursion with finite memory is impossible.

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].

Code B.13-46: Boolean Expressions


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
int main () {
int p = 0 , q = 0;
cout <<
cout <<
( p || ! p )
cout << (!( p && ! p ))
cout << (!( p && q ) == (! p || ! q ))
cout << (!( p || q ) == (! p && ! q ))
return 0;
}

192

<<
<<
<<
<<

" <" ;
" ," ;
" ," ;
" ," ;
" >" ;

APPENDIX B. SELF-TESTS

B.13. FINAL

[40] If-Elseif : L. 2 Comprehension (Chemistry). Hydrocarbons take the form Cn Hm . If m = 2n + 2 the


hydrocarbon is called an alkane; if m = 2n it is an alkene, and if m = 2n 2 it is an alkyne. Given that,
what does the following program print for a, b values of h2, 6i, h2, 4i, h2, 2i, and h4, 2i [4x10]?

Code B.13-47: If-Else


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
int main () {
int
a,
cin >> a >>
if ( b
else if ( b
else if ( b
else
return 0;
}

b;
b;
== 2* a + 2) cout <<
== 2* a
) cout <<
== 2* a - 2) cout <<
cout <<

" alkane " ;


" alkene " ;
" alkyne " ;
"?";

[40] Switch: L. 2 Comprehension (Computer Science, Mathematics). What happens when I put in a values
of h1, 2, 3, 4i [4x10]?

Code B.13-48: Switch


1
2

# include < iostream >


using namespace std ;

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]?

Code B.13-49: If-Elseif-Else


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# include < iostream >


using namespace std ;
int main () {
cout << " On a scale of 1 ( very sad ) to 7 ( very happy ) , " << endl ;
<< " how happy are you ? > " ;
int
response ;
cin >> response ;
if ( response > 6) cout << " :) " ;
if ( response > 5) cout << " :) " ;
if ( response > 4) cout << " :) " ;
if ( response < 4) cout << " :( " ;
if ( response < 3) cout << " :( " ;
if ( response < 2) cout << " Cheer up ! " ;
if ( response == 4) cout << " :| " ;
cout << endl ;
return 0;
}

[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].

Code B.13-50: If-Else; Boolean Logic


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# include < iostream >


using namespace std ;
int main () {
bool a , b , c ;
cout << " Enter a : " ; cin >>
a;
cout << " Enter b : " ; cin >>
b;
cout << " Enter c : " ; cin >>
c;
if
( a && b )
cout << 0 ;
else
cout << 1 ;
if
( a || ! b )
cout << 0 ;
else
cout << 1 ;
if
( a && c )
cout << 0 ;
else
cout << 1 ;
if
( b || ! c )
cout << 0 ;
else
cout << 1 ;
return 0;
}

194

APPENDIX B. SELF-TESTS

B.13. FINAL

[40] Nested If-Else: L. 3 Comprehension (Philosophy). What does the following program print [40]?

Code B.13-51: Nested If-Else


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# include < iostream >


using namespace std ;
int main () {
if ( true )

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 );

cout << ( ! true &&

true );

cout << ( ! true &&

! true );

cout << ( false &&

true );

cout << ( false &&

! true );

cout << (! false &&

false );

cout << (

true &&

true );

cout << (

true &&

! true );

cout << ( ! true &&

false );

cout << ( ! true && ! false );


( true )

else
else

true &&

true && ! false );

cout << (! false && ! false );

else
else

cout << (
cout << (

( false )

cout << ( false &&

true );

cout << ( false &&

! true );

cout << (! false &&

false );

cout << (! false && ! 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].

Code B.13-52: For; Debugging


1
2
3
4
5
6
7
8
9
10
11
12

# include < iostream >


using namespace std ;
int main () {
int i , c =10 , s =0;
cin >> c ;
for ( i ; i = c ; i +=1)
s += i ;
cout << i << " : " ;
cout << n << " \ n " ;
return 0;
}

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].

Code B.13-53: Off-By-One


1
2
3
4
5
6
7
8

for
for
for
for
for
for
for
for

( i =0; false ; i ++); cout << i ;


( i =0; true ; i ++); cout << i ;
( i =0; i <=0; i ++); cout << i ;
( i =0; i >=0; i ++); cout << i ;
( i =0; false ; i - -); cout << i ;
( i =0; true ; i - -); cout << i ;
( i =0; i <=0; i - -); cout << i ;
( i =0; i >=0; i - -); cout << i ;

[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]?

Code B.13-54: Off-By-One


1 float t =0.0 , A =128.0 , R =8000.0;
2 for ( f =800.0; f <=1600.0; f +=1) {
3
t =0;
4
while ( t < 2* R ) {
5
t ++;
6
cout << ( uint8_t ) A * sin (2* M_PI * f * t / R );
7
}
8 }

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]?

Code B.13-55: If Inside Do-While


1
2
3
4
5
6
7
8
9
10
11
12
13
14

# include < iostream >


using namespace std ;
int main () {
int c ;
cin >> c ;
do {
if ( c > 0) c ++;
else
c - -;
c *= -1;
cout << c ;
} while ( abs ( c ) < 5);
return 0;
}

[20] Function Calls: L. 1 Comprehension (Mathematics). Print the outputs of the top-level function calls
in the following snippet [4x5].

Code B.13-56: Function Calls


1
2
3
4
5
6
7
8
9
10
11

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 . . .

Code B.13-57: Function Arguments


1
2
3
4
5
6
7
8
9
10
11
12

void f ( int c , int b , int a );


int main () {
int a =0 , b =1 , c =1 , d =1 , e =2 , f =4;
f (f , e , d , c , b , a );
}
void f ( int f ,
cout << a
<< c
<< e
}

int b , int e , int a , int c , int d ) {


<< b
<< d
<< f ;

[60] Function Calls: L. 3 Comprehension (Computer Science). Print the output for the calls on Line 7 and
Line 8 [30=3x2x10].

Code B.13-58: Call Hierarchy


1
2
3
4
5
6
7
8
9
10

int foo ( int a , int b ) {


cout << b ;
return a ;
}
int main () {
foo ( foo ( foo (1 , 2) , 3) , 4);
foo (1 , foo (2 , foo (3 , 4)));
return 0;
}

198

APPENDIX B. SELF-TESTS

B.13. FINAL

[20] Structs: L. 2 Comprehension (Mathematics). Print the output of the following [10x2].

Code B.13-59: Arrays


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# include < iostream >


using namespace std ;
struct imag {
float a ;
float b ;
};
struct imag mul ( struct imag A , struct imag B ) {
struct imag C ;
C . a = ( A . a * B . a - A . b * B . b );
C . b = ( A . b * B . a + A . a * B . b );
return C ;
}
int main () {
struct imag A ,
A . a = 1.0; A . b
B . a = 3.0; B . b
C = mul (A , B );
cout << C . a <<
}

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].

Code B.13-60: Arrays


1
2
3
4
5
6
7
8
9

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

[20] Binary Conversion: L. 1 Application (Computer Science) Convert 101010102 to decimal.

[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].

Code B.13-61: Nesting If in For


1
2
3

for ( i = __ ; __0 ; ___ )


if ( _ % _ == _ )
cout << _ << " " ;

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].

Where ~a is an integer vector,


define Algorithm Selection Sort(~a):
1. Let n size(~a).
2. For i in range [0, n):
(a) Let j find next argmin(~a, i).
(b) Call swap(ai , aj ).
3. Return ~a.

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].

Code B.13-62: Stat


1
2
3
4
5
6
7
8
9
10
11

# include " curve . h "


using namespace crv ;
int main () {
float factor =.1;
int grades [4] = {36 , 12 , 14 , 24};
crv :: sort ( grades );
crv :: quadscale ( grades , factor );
int sum = crv :: roundup ( grades , 5);
cout << sum ;
}

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

index; element of a set

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

Pseudocode Word Bank

for

while

do

until

if

else

then

range

each

all

let

return

208

Appendix E

Algorithms

Contents
E.1

Computer Science . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210

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

E.1. COMPUTER SCIENCE

APPENDIX E. ALGORITHMS

E.1

Computer Science

E.1.1

Manhattan Distance

Where

~x
~y

:
:

vector (int)
vector (int)

define Algorithm Manhattan(~x, ~y ):

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

E.1. COMPUTER SCIENCE

Minima and Maxima

Where

~v

vector(int)

vector to find minimum in

vector to find maximum in

define Algorithm Find Minimum(~v ):

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)

define Algorithm Find Maximum(~v ):

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. COMPUTER SCIENCE

E.1.3

APPENDIX E. ALGORITHMS

Argmin and Argmax

Where

~v

vector(int)

vector to find argmin in

define Algorithm Find Argument of Minimum(~v ):

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)

vector to find maximum in

define Algorithm Find Argument of Maximum(~v ):

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

define Algorithm Sum(n):

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)

define Algorithm Dot Product(~u, ~v ):

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)

define Algorithm Cross Product(~u, ~v ):

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

define Algorithm Transpose Matrix(A, B):

1. For i in the range [0, N ):


(a) For j in the range [0, M ):
i. Let Bji Aij .

216

APPENDIX E. ALGORITHMS

E.3

E.3.1

E.3. PHYSICS

Physics

Modelling a Projectile Object

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

define Algorithm Throw Ball():

1. Let t 0.
2. While (t 60):
(a) Let x t.
(b) Let y

2t2
N

t + M.

(c) Call print board(x, y).


(d) Wait for n s.
(e) Clear the screen.

217

E.4. CHEMISTRY

E.4

E.4.1

APPENDIX E. ALGORITHMS

Chemistry

Ideal Gas Equation

Where

v
t
R

:
:
:

float
float
float

:
:
:

volume
temperature
gas constant

define Algorithm Pressure(v, t):

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

define Algorithm Pressures(v1 , v2 , vs , t1 , t2 , ts ):

1. For each v in the range of [v1 , v2 ], in increments of vs :


(a) For each t in the range of [t1 , t2 ], in increments of ts :
i. Output v, t, pressure(v, t).

218

APPENDIX E. ALGORITHMS

E.5

E.5.1

E.5. BIOLOGY

Biology

RNA Transcription

Where

r
d

:
:

string
string

define Algorithm Transcribe RNA(r):

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

Generating Truth Tables

Where

p
q
...
c

:
:
:
:

bool
bool
...
conditional to test

define Algorithm Truth Tables():

1. For p in range [0, 1]:


(a) For q in range [0, 1]:
i. . . .
A. Output p, q, . . . , c.

220

APPENDIX E. ALGORITHMS

E.6.2

E.6. PHILOSOPHY

Zenos Paradox

Where

D
d

:
:

float
float

:
:

a total distance
distance walked to

define Algorithm Zenos Paradox():

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

define Algorithm Blink Text(a, b, ta , tb ):

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)

:
:
:

Size-M vector containing ones test data


A vector of Manhattan distances between ones test vector and others
N M matrix of test data

define Algorithm Find Similar Person(P, ~v ):

1. For i in range [0, N ):


(a) Let ~u pi .
(b) Let di manhattan(~u, ~v ).
~
2. Return argmin(d).

223

E.8. LINGUISTICS

E.8

E.8.1

APPENDIX E. ALGORITHMS

Linguistics

String Reversal

Where

string

string to reverse

define Algorithm Reverse String(n):

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

string to tell if palindrome

define Algorithm Detect Palindrome(s):

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

Ball Throw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228

F.2

Boolean Switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229

F.3

Cross Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230

F.4

De Morgans Truth Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

F.5

Double Summation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232

F.6

For Creating Flowcharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233

F.7

Ideal Gas Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234

F.8

Ionic Reaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235

F.9

Manhattan Distance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236

F.10 Transposing a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237


F.11 Dealing a Poker Hand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
F.12 For Writing Pseudocode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
F.13 Reversing the Boolean Switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
F.14 Reversing a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
F.15 Summation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
F.16 RNA Transcription . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

227

F.1. BALL THROW

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

Print board with


ball at x, y

Finish

228

APPENDIX F. FLOWCHARTS

F.2

F.2. BOOLEAN SWITCH

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. CROSS PRODUCT

F.3

APPENDIX F. FLOWCHARTS

Cross Product

Start

Start

Let w1 <u2v3 - u3v2

Input
u and v

Let w2 <u3v1 - u1v3

cross(u, v)

Let w3 <u1v2 - u2v1

Output w

Finish

Return

230

APPENDIX F. FLOWCHARTS

F.4

F.4. DE MORGANS TRUTH TABLES

De Morgans Truth Tables

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. DOUBLE SUMMATION

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

F.6. FOR CREATING FLOWCHARTS

For Creating Flowcharts

Identify set of inputs I,


and draw parallelograms
around them

Read P critially.
Scan for relevant
information.

Start

true

Example
problem
solved?

false

Identify the output O. If


it is output to stdout
draw a parallelogram,
otherwise a bubble

Flowchart
can solve
example?

false

true

First time
solving the
problem?

true

Do and write down


the next step in
solving the
example problem.,
Draw a box around it.

false

Delete or insert
steps, re-draw
arrows to try to
solve example

233

Finish

F.7. IDEAL GAS EQUATION

F.7

APPENDIX F. FLOWCHARTS

Ideal Gas Equation

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

F.8. IONIC REACTION

Ionic Reaction

Input a, b

Start

Output sa

Output " + "

sb==1?

Let ca <abs(charge(a))

Let cb <abs(charge(b))

Let sa <symbol(a)

Let sb <symbol(b)

Output " -> "

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. MANHATTAN DISTANCE

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

Let d <- d + |x_i - y_i|


Let i <- i + 1

APPENDIX F. FLOWCHARTS

F.10

F.10. TRANSPOSING A MATRIX

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

Let B[j][i] <- A[i][j]

Output B

237

F.11. DEALING A POKER HAND

F.11

APPENDIX F. FLOWCHARTS

Dealing a Poker Hand

Start

Finish
Let r = rand()

false

true

Let r <- rand()


Let i <- 0

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

F.12. FOR WRITING PSEUDOCODE

For Writing Pseudocode

Identify set of inputs I,


their types, and
descriptions

Read P critially.
Scan for relevant
information.

Start

true

Example
problem
solved?

false

Identify the output O and


whether or not it is
stdout output, file output,
or returned

Pseudocode
can solve
example?

false

true

First time
solving the
problem?

true

Do and write down


the next step in
solving the
example problem.

false

Re-order, modify,
insert, or delete
steps until the
problem is solved.

239

Finish

F.13. REVERSING THE BOOLEAN SWITCH

F.13

APPENDIX F. FLOWCHARTS

Reversing the Boolean Switch

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

F.14. REVERSING A STRING

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

F.16. RNA TRANSCRIPTION

RNA Transcription

Start

Finish

false

Let n <- size(r)


Let i <- 0

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

Let d_i <- U

Let d_i <- C

Let d_i <- G

243

Let d_i <- A

Anda mungkin juga menyukai