0% found this document useful (0 votes)
111 views71 pages

Growing Algorithms & Data Structures

Scuse

Uploaded by

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

Growing Algorithms & Data Structures

Scuse

Uploaded by

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

Download the full version of the ebook at

https://ebookultra.com

Growing Algorithms and Data Structures 4th


Edition David Scuse

https://ebookultra.com/download/growing-
algorithms-and-data-structures-4th-edition-david-
scuse/

Explore and download more ebook at https://ebookultra.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Data Structures and Algorithms in Java 4th Edition Michael


T. Goodrich

https://ebookultra.com/download/data-structures-and-algorithms-in-
java-4th-edition-michael-t-goodrich/

ebookultra.com

Java Collections An Introduction to Abstract Data Types


Data Structures and Algorithms 1st Edition David A. Watt

https://ebookultra.com/download/java-collections-an-introduction-to-
abstract-data-types-data-structures-and-algorithms-1st-edition-david-
a-watt/
ebookultra.com

Learning JavaScript Data Structures and Algorithms 2nd


Edition Loiane Groner

https://ebookultra.com/download/learning-javascript-data-structures-
and-algorithms-2nd-edition-loiane-groner/

ebookultra.com

Learning F Functional Data Structures and Algorithms 1st


Edition Masood

https://ebookultra.com/download/learning-f-functional-data-structures-
and-algorithms-1st-edition-masood/

ebookultra.com
Data Structures Algorithms In Go 1st Edition Hemant Jain

https://ebookultra.com/download/data-structures-algorithms-in-go-1st-
edition-hemant-jain/

ebookultra.com

Concise Notes on Data Structures and Algorithms Ruby


Edition Christopher Fox

https://ebookultra.com/download/concise-notes-on-data-structures-and-
algorithms-ruby-edition-christopher-fox/

ebookultra.com

Data Structures and Algorithms in Java 6th Edition Michael


T. Goodrich

https://ebookultra.com/download/data-structures-and-algorithms-in-
java-6th-edition-michael-t-goodrich/

ebookultra.com

Data Structures and Algorithms Using Python 1st Edition


Rance D. Necaise

https://ebookultra.com/download/data-structures-and-algorithms-using-
python-1st-edition-rance-d-necaise/

ebookultra.com

AI algorithms data structures and idioms in Prolog Lisp


and Java 6th Edition George F. Luger

https://ebookultra.com/download/ai-algorithms-data-structures-and-
idioms-in-prolog-lisp-and-java-6th-edition-george-f-luger/

ebookultra.com
Growing Algorithms and Data Structures 4th Edition
David Scuse Digital Instant Download
Author(s): David Scuse
ISBN(s): 9780100007369, 0100007368
Edition: 4th
File Details: PDF, 3.23 MB
Year: 2011
Language: english
Growing

Algorithms

And

Data Structures

(Fourth Edition)

© David Scuse
Department of Computer Science
University of Manitoba
June, 2011
GROWING ALGORITHMS AND DATA STRUCTURES

INTRODUCTION ................................................................................................................ 1
1 PROCEDURAL PROGRAMMING ................................................................................... 3
1.1 INTRODUCTION ........................................................................................................... 3
1.2 PROGRAMMING ............................................................................................................ 3
1.3 HELLO WORLD ............................................................................................................ 4
1.4 COMMENTS ................................................................................................................ 5
1.5 ASSIGNMENT STATEMENT ................................................................................................ 6
1.6 CONDITIONAL EXECUTION ............................................................................................... 8
1.7 LOOPS ................................................................................................................... 12
1.8 FUNCTIONS/METHODS ................................................................................................. 13
1.9 LISTS/ARRAYS .......................................................................................................... 14
1.10 PASSING PARAMETERS ............................................................................................. 19
1.11 SCOPE ............................................................................................................... 22
1.12 DATA TYPES ......................................................................................................... 22
1.13 STRINGS ............................................................................................................. 24
1.14 MODULES/CLASSES ................................................................................................ 26
1.15 DETERMINING PRIME NUMBERS ................................................................................... 27
1.16 DIFFERENCES BETWEEN PYTHON 2 AND PYTHON 3 .............................................................. 29
1.17 DIFFERENCES BETWEEN PYTHON AND JAVA ...................................................................... 29
1.18 SUMMARY ............................................................................................................ 29
2 GROWING ALGORITHMS ......................................................................................... 31
2.1 INTRODUCTION ......................................................................................................... 31
2.2 SEARCHING A LIST ..................................................................................................... 31
2.2.1 Linear Search................................................................................................. 33
2.2.2 Linear Search of an Ordered List ....................................................................... 36
2.2.3 Binary Search ................................................................................................ 38
2.3 SEARCHING A LIST OF STRINGS ...................................................................................... 40
2.4 RECAP ................................................................................................................... 41
2.5 ARRAY INITIALIZATION ................................................................................................. 41
2.6 CONDITIONAL OPERATOR .............................................................................................. 42
2.7 THE FOR STATEMENT................................................................................................... 43
2.8 SYSTEM.ARRAYCOPY .................................................................................................... 45
2.9 ROTATING THE ELEMENTS IN AN ARRAY .............................................................................. 46
2.10 GENERATING PRIME NUMBERS .................................................................................... 47
2.11 GENERATING SEQUENCES OF VALUES ............................................................................ 48
2.12 GENERATING A FREQUENCY COUNT OF VALUES ................................................................. 49
2.13 MERGE ALGORITHM ................................................................................................. 50
2.14 MERGING STRINGS ................................................................................................. 58
2.15 PARALLEL ARRAYS .................................................................................................. 59
2.15.1 Maintaining the Number of Elements in the Arrays .......................................... 60
2.15.2 Using a Sentinel Value ................................................................................. 63
2.15.3 Copying the Arrays ..................................................................................... 65
2.15.4 Global Variables.......................................................................................... 67
2.15.5 Recap ....................................................................................................... 68
2.16 GROWING ALGORITHMS ............................................................................................ 69
2.17 DEBUGGING ......................................................................................................... 70
2.18 TESTING ............................................................................................................. 74
2.19 DEFENSIVE PROGRAMMING ........................................................................................ 74
2.20 ALGORITHM EFFICIENCY ............................................................................................ 74
2.21 SUMMARY ............................................................................................................ 76

i
3 OBJECTS .................................................................................................................. 77
3.1 INTRODUCTION ......................................................................................................... 77
3.2 DATA TYPES ............................................................................................................. 77
3.3 BASIC OBJECT STRUCTURE ............................................................................................ 77
3.4 WHAT IS AN OBJECT? .................................................................................................. 82
3.5 SIMPLE CLASS STRUCTURE ............................................................................................ 83
3.6 VISIBILITY MODIFIERS ................................................................................................. 85
3.7 MANIPULATING AN OBJECT ............................................................................................ 85
3.8 CLASSES AND INSTANCES ............................................................................................. 86
3.9 STATE INFORMATION ................................................................................................... 87
3.10 ARRAYS OF OBJECTS ............................................................................................... 89
3.11 CLASS VARIABLES AND CLASS METHODS ........................................................................ 92
3.12 WRAPPER CLASSES ................................................................................................. 93
3.13 IMMUTABLE OBJECTS ............................................................................................... 95
3.14 COMPARING OBJECTS .............................................................................................. 96
3.15 ENCAPSULATION AND INFORMATION HIDING ..................................................................... 98
3.16 FACTORY METHOD .................................................................................................. 98
3.17 THE MAIN CLASS ................................................................................................... 99
3.18 SUMMARY .......................................................................................................... 100
4 FILE INPUT AND OUTPUT ...................................................................................... 103
4.1 INTRODUCTION ....................................................................................................... 103
4.2 SCANNER CLASS ...................................................................................................... 103
4.3 BUFFERED FILE INPUT ................................................................................................ 103
4.4 FILE OUTPUT .......................................................................................................... 105
4.5 RECAP ................................................................................................................. 107
4.6 MERGING FILES ....................................................................................................... 108
4.7 TWO USEFUL TEXTPAD FEATURES .................................................................................. 113
4.8 EXCEPTIONS........................................................................................................... 113
4.8.1 Thowing Exceptions ...................................................................................... 115
4.8.2 Programmer-Defined Exceptions ..................................................................... 116
4.9 AN INPUT/OUTPUT PROCESSING CLASS ........................................................................... 117
5 STRINGS ............................................................................................................... 121
5.1 INTRODUCTION ....................................................................................................... 121
5.2 CHARACTER MANIPULATION ......................................................................................... 121
5.3 CHARACTER WRAPPER CLASS ....................................................................................... 123
5.4 STRINGS............................................................................................................... 124
5.5 STRING METHODS .................................................................................................... 126
5.6 STRING COMPARISON ................................................................................................ 128
5.7 STRINGS ARE OBJECTS .............................................................................................. 129
5.8 STRINGS ARE IMMUTABLE ............................................................................................ 131
5.9 DATA VALIDATION .................................................................................................... 132
5.10 STRING FORMATTING ............................................................................................. 133
5.11 STRING PROCESSING ............................................................................................. 136
5.12 STRING TOKENIZING ............................................................................................. 138
5.12.1 Extracting Tokens ..................................................................................... 138
5.12.2 String Split Method ................................................................................... 139
5.13 BINARY SEARCH OF AN ARRAY OF STRINGS .................................................................... 139
5.14 PATTERN MATCHING .............................................................................................. 140
5.15 MORE PATTERN MATCHING ...................................................................................... 142
5.16 COUNTING CHARACTERS ......................................................................................... 143
5.17 A MUTABLE STRING CLASS ...................................................................................... 145
5.18 STRINGBUFFER CLASS ........................................................................................... 146
5.18.1 StringBuffer Methods................................................................................. 146
5.18.2 Using a StringBuffer Object ........................................................................ 147

ii
6 OBJECT EXAMPLES ................................................................................................ 149
6.1 INTRODUCTION ....................................................................................................... 149
6.2 PERSON EXAMPLE..................................................................................................... 149
6.3 VIDEO STORE EXAMPLE .............................................................................................. 150
6.4 EMPLOYEE EXAMPLE .................................................................................................. 151
6.5 GST ACCOUNT EXAMPLE ............................................................................................ 153
6.6 COFFEE SHOP EXAMPLE .............................................................................................. 154
6.6.1 Iteration 1 ................................................................................................... 154
6.6.2 Iteration 2 ................................................................................................... 155
6.6.3 Iteration 3 ................................................................................................... 156
6.6.4 Iteration 4 ................................................................................................... 157
6.6.5 Recap ......................................................................................................... 159
6.7 WORDS CLASS........................................................................................................ 159
7 OBJECT REPRESENTATION .................................................................................... 163
7.1 INTRODUCTION ....................................................................................................... 163
7.2 OBJECT REFERENCES ................................................................................................. 163
7.3 ARRAYS ARE OBJECTS ................................................................................................ 165
7.4 STRINGS............................................................................................................... 168
7.4.1 Strings are Immutable .................................................................................. 169
7.5 PASSING PARAMETERS ............................................................................................... 170
7.6 CLONING OBJECTS ................................................................................................... 174
7.7 INFORMATION ABOUT OBJECTS ..................................................................................... 175
7.8 SUMMARY ............................................................................................................. 175
8 OBJECT ORIENTATION PRACTICES ........................................................................ 177
8.1 INTRODUCTION ....................................................................................................... 177
8.2 BASIC CLASS STRUCTURE ........................................................................................... 177
8.3 REMOVE ACCESSORS AND MUTATORS .............................................................................. 182
8.4 MOVE OBJECT PROCESSING INTO ITS OWN CLASS ................................................................ 184
8.5 USING FILE INPUT .................................................................................................... 186
8.6 USING A FACTORY METHOD ......................................................................................... 187
8.7 COMPLETE CREDIT-CARD EXAMPLE ................................................................................. 188
8.8 SUMMARY ............................................................................................................. 192
9 OBJECT COLLECTIONS ........................................................................................... 193
9.1 INTRODUCTION ....................................................................................................... 193
9.2 ARRAYLISTS........................................................................................................... 193
9.3 COMPILING ARRAYLISTS ............................................................................................. 195
9.4 ARRAYLIST METHODS ................................................................................................ 196
9.5 CASTING .............................................................................................................. 197
9.6 REVERSING THE ELEMENTS IN AN ARRAYLIST ..................................................................... 198
9.7 SEARCHING AN ARRAYLIST .......................................................................................... 199
9.8 PRINTING THE CONTENTS OF AN ARRAYLIST ....................................................................... 201
9.9 ROTATING THE CONTENTS OF AN ARRAYLIST ...................................................................... 201
9.10 INSERTING INTO AN ARRAYLIST IN ASCENDING ORDER ...................................................... 202
9.11 SEARCHING AN ARRAYLIST OF INTEGERS WITH A BINARY SEARCH .......................................... 202
9.12 SEARCHING AN ARRAYLIST OF STRINGS WITH A BINARY SEARCH ........................................... 203
9.13 CREDIT-CARDS EXAMPLE ........................................................................................ 204
9.14 GENERICS ......................................................................................................... 206
9.15 BOXING AND UNBOXING ......................................................................................... 207
9.16 OUR VERSION OF ARRAYLIST.................................................................................... 208
9.17 ARRAYLIST ALGORITHMS......................................................................................... 209
9.18 PROCESSING COURSE MARKS ................................................................................... 210
9.19 SUMMARY .......................................................................................................... 214

iii
10 OBJECT HIERARCHIES ........................................................................................... 215
10.1 INTRODUCTION .................................................................................................... 215
10.2 OBJECTS ........................................................................................................... 215
10.3 ANIMALS EXAMPLE ................................................................................................ 216
10.4 CLASS HIERARCHIES ............................................................................................. 219
10.5 VISIBILITY ......................................................................................................... 220
10.6 INHERITING AND OVERRIDING METHODS....................................................................... 221
10.7 CONSTRUCTORS IN HIERARCHIES ............................................................................... 224
10.8 CASTING OBJECTS ................................................................................................ 227
10.9 INSTANCEOF ....................................................................................................... 228
10.10 CLASS VARIABLES AND CLASS METHODS ...................................................................... 229
10.11 CLASS OBJECT .................................................................................................... 230
10.12 ARRAYS ARE OBJECTS ............................................................................................ 231
10.13 COLLECTIONS OF OBJECTS ....................................................................................... 231
10.14 ARRAYLISTS ....................................................................................................... 233
10.15 GENERICS ......................................................................................................... 234
10.16 DRIVER’S LICENSE EXAMPLE ..................................................................................... 235
10.17 RECAP .............................................................................................................. 238
10.18 SUMMARY .......................................................................................................... 238
11 MORE OBJECT HIERARCHY TOPICS ....................................................................... 239
11.1 INTRODUCTION .................................................................................................... 239
11.2 POLYMORPHISM ................................................................................................... 239
11.3 ABSTRACT CLASSES .............................................................................................. 245
11.4 INHERITING AND SHADOWING VARIABLES ..................................................................... 246
12 OBJECT HIERARCHY EXAMPLES ............................................................................. 249
12.1 INTRODUCTION .................................................................................................... 249
12.2 BANK ACCOUNT EXAMPLE ........................................................................................ 249
12.2.1 Recap ..................................................................................................... 252
12.3 CREDIT CARD EXAMPLE .......................................................................................... 252
12.4 STOCK PORTFOLIO EXAMPLE ..................................................................................... 255
12.4.1 Iteration 1 ............................................................................................... 256
12.4.2 Iteration 2 ............................................................................................... 258
12.4.3 Iteration 3 ............................................................................................... 259
12.4.4 Iteration 4 ............................................................................................... 263
12.4.5 Iteration 5 ............................................................................................... 267
12.4.6 Iteration 6 ............................................................................................... 268
12.4.7 Iteration 7 ............................................................................................... 269
12.4.8 Iteration 8 ............................................................................................... 271
12.4.9 Iteration 9 ............................................................................................... 271
12.4.10 Complete Stock Portfolio Example ............................................................... 272
12.4.11 Recap ..................................................................................................... 277
12.5 SUMMARY .......................................................................................................... 277
13 SORTING ............................................................................................................... 279
13.1 INTRODUCTION .................................................................................................... 279
13.2 BUBBLE SORT ..................................................................................................... 279
13.3 SELECTION SORT ................................................................................................. 282
13.4 INSERTION SORT ................................................................................................. 284
13.5 SORTING AN ARRAY OF STRINGS ................................................................................ 286
13.6 SORTING INTO DESCENDING ORDER............................................................................ 287
13.7 SUMMARY .......................................................................................................... 287
14 RECURSION ........................................................................................................... 289
14.1 INTRODUCTION .................................................................................................... 289
14.2 ITERATION ......................................................................................................... 289
14.3 RECURSION ........................................................................................................ 290

iv
14.4 PROCESSING STRINGS ........................................................................................... 293
14.4.1 String Reverse ......................................................................................... 293
14.4.2 Palindromes ............................................................................................. 294
14.4.3 String Padding .......................................................................................... 295
14.4.4 Number Conversions ................................................................................. 295
14.5 PROCESSING ARRAYS............................................................................................. 296
14.6 BINARY SEARCH .................................................................................................. 299
14.7 RECURSIVE MERGE ............................................................................................... 300
14.8 PROCESSING ARRAYLISTS ....................................................................................... 300
14.9 FIBONACCI NUMBERS ............................................................................................. 301
14.10 PROCESSING OBJECTS ........................................................................................... 303
14.11 THE RECURSION STACK .......................................................................................... 304
14.12 ITERATION VERSUS RECURSION ................................................................................. 306
14.13 RECURSION EXAMPLES ........................................................................................... 307
14.13.1 Palindrome .............................................................................................. 307
14.13.2 Reversing Words....................................................................................... 307
14.13.3 Filling an Array ......................................................................................... 308
14.13.4 Precomputing Values ................................................................................. 308
14.13.5 Frequency Count ...................................................................................... 309
15 LINKED LISTS ....................................................................................................... 311
15.1 INTRODUCTION .................................................................................................... 311
15.2 LISTS .............................................................................................................. 311
15.3 ARRAYS ............................................................................................................ 311
15.4 A SIMPLE LINKED LIST ........................................................................................... 311
15.5 A BETTER LINKED LIST ........................................................................................... 314
15.6 A LINKED LIST CLASS ............................................................................................ 316
15.7 INSERTING AT THE BEGINNING OF A LINKED LIST ............................................................. 319
15.8 INSERTING AT THE END OF A LINKED LIST ..................................................................... 320
15.9 DELETING AN ELEMENT ........................................................................................... 321
15.10 LINKED LIST EXAMPLES .......................................................................................... 326
15.10.1 Find Last Node ......................................................................................... 326
15.10.2 Print String Objects ................................................................................... 327
15.10.3 Print Adjacent String Objects ...................................................................... 327
15.10.4 Reverse List Elements ............................................................................... 328
15.10.5 Add Back Links ......................................................................................... 328
15.10.6 Split a List into Two Lists ........................................................................... 328
15.10.7 Rotating the Contents of a Linked List.......................................................... 329
15.10.8 Remove String Objects .............................................................................. 330
15.11 RECAP .............................................................................................................. 330
15.12 SUMMARY .......................................................................................................... 331
16 MULTI-DIMENSIONAL ARRAYS .............................................................................. 333
16.1 INTRODUCTION .................................................................................................... 333
16.2 ONE-DIMENSIONAL ARRAYS ..................................................................................... 333
16.3 MULTI-DIMENSIONAL ARRAYS ................................................................................... 333
16.4 MATRICES ......................................................................................................... 335
16.5 MATRIX OBJECT ................................................................................................... 337
16.6 ARRAY INITIALIZATION ........................................................................................... 339
16.7 ARRAYS OF OBJECTS ............................................................................................. 339
16.8 TIC-TAC-TOE ..................................................................................................... 340
17 GENERIC DATA STRUCTURES ................................................................................ 343
17.1 INTRODUCTION .................................................................................................... 343
17.2 GENERIC LINKED LIST ............................................................................................ 343
17.3 USING COMPARETO ............................................................................................... 345
17.4 JAVA’S GENERICS ................................................................................................. 346
17.5 USING COMPARETO WITH GENERICS ............................................................................ 349

v
17.6 USING A JAVA INTERFACE ........................................................................................ 349
18 GROWING AND REFACTORING .............................................................................. 353
18.1 INTRODUCTION .................................................................................................... 353
18.2 REFACTORING ..................................................................................................... 353
18.2.1 Rename Method ....................................................................................... 353
18.2.2 Extract Method ......................................................................................... 353
18.2.3 Convert Procedural Design to Objects .......................................................... 354
18.2.4 Comments ............................................................................................... 354
18.3 DESIGN ............................................................................................................ 354
18.4 FLIGHTS EXAMPLE ................................................................................................ 355
18.4.1 Iteration 1 ............................................................................................... 355
18.4.2 Iteration 2 ............................................................................................... 356
18.4.3 Iteration 3 ............................................................................................... 358
18.4.4 Iteration 4 ............................................................................................... 359
18.4.5 Iteration 5 ............................................................................................... 361
18.4.6 Iteration 6 ............................................................................................... 363
18.4.7 Iteration 7 ............................................................................................... 364
18.4.8 Iteration 8 ............................................................................................... 365
18.4.9 Iteration 9 ............................................................................................... 367
18.4.10 Iteration 10 ............................................................................................. 367
18.4.11 Iteration 11 ............................................................................................. 369
18.5 COMPLETE FLIGHTS EXAMPLE .................................................................................... 370
18.6 SUMMARY .......................................................................................................... 375
19 MISCELLANEOUS TOPICS ...................................................................................... 377
19.1 INTRODUCTION .................................................................................................... 377
19.2 SYSTEM STREAMS................................................................................................. 377
19.3 FILE PROCESSING WRAPPER CLASSES .......................................................................... 381
19.4 BUFFERED CONSOLE INPUT ...................................................................................... 382
19.5 FILES AND THE END-OF-LINE CHARACTER(S) ................................................................. 384
19.6 NON-RECTANGULAR ARRAYS .................................................................................... 384
19.7 PARALLEL ARRAYS ................................................................................................ 385
19.8 HIGHER DIMENSIONAL ARRAYS ................................................................................. 386
19.9 MERGE SORT ...................................................................................................... 387
19.10 QUICKSORT ....................................................................................................... 388
19.11 SORTING A LINKED LIST ......................................................................................... 389
19.12 BINARY TREES .................................................................................................... 393
19.13 TOWERS OF HANOI ............................................................................................... 395
19.14 SYSTEM PROPERTIES ............................................................................................. 397
19.15 INFORMATION ABOUT OBJECTS .................................................................................. 397
19.16 THE SYSTEM TIMER ............................................................................................... 398
19.17 THE STACK TRACE ................................................................................................ 399
19.18 GARBAGE COLLECTION ........................................................................................... 400
19.19 THE HEAP.......................................................................................................... 400
19.20 THE OBJECT HIERARCHY ......................................................................................... 401
19.21 CHANGING THE HASH CODE ..................................................................................... 402
19.22 FILE DIRECTORY PROCESSING ................................................................................... 402
19.23 RECURSIVE FILE DIRECTORY PROCESSING ..................................................................... 403
19.24 STACK-BASED FILE DIRECTORY PROCESSING ................................................................. 404
19.25 CREATING OBJECTS DYNAMICALLY .............................................................................. 406
19.26 CALLING METHODS DYNAMICALLY .............................................................................. 407
19.27 POLYMORPHISM WITHOUT HIERARCHIES ........................................................................ 408
19.28 COMPILING AND EXECUTING A JAVA PROJECT .................................................................. 411
19.29 SUMMARY .......................................................................................................... 413
INDEX........................................................................................................................... 415

vi
INTRODUCTION

Courses such as COMP 1010 and COMP 1012 focus on developing algorithms using
primitive data types (ints, doubles, etc.), conditions, loops, arrays, and methods. These are the
basic building blocks of computer programming and this style of programming is referred to
as “procedural programming”. In COMP 1020, we examine how these building blocks can
be put together to solve more complex problems. At the same time, we also make the
transition from procedural programming to object-oriented programming. Writing good
object-oriented programs is not easy, it takes some time to stop thinking in a procedural
manner and start thinking in an object-oriented manner.

Our study of algorithms concentrates on the development of algorithms that work correctly
and are easy to understand. We will not be concerned with developing algorithms that are as
efficient as possible. We will note where certain algorithms are inefficient and could be
improved but we will not attempt to make each algorithm optimal in terms of its memory
requirements and/or execution time.

In COMP 1010 and COMP 1012, the organization of each program in an assignment was
normally described in class. In this course, the organization of solution for assignments will
not be given; instead, the student is expected to develop the structure of each program by
him/herself (with some hints from the instructor). Instead of developing the entire program at
once, the program will be developed (“grown”) slowly. We will concentrate on “doing the
simplest thing that works”, in other words, develop a simple, incomplete version of the
algorithm that executes correctly and then gradually improve the algorithm until it provides
the required functionality (start small and grow slowly). We will not add functionality that
is not explicitly required!

“Simple systems are easier to build, easier to maintain, smaller, and faster than
complex ones. A simple system ‘maximizes the work done’, by increasing ‘the
amount of work not done’. A program must do exactly what’s required by the
user. Adding unasked-for-functionality dramatically increases the development
time and decreases stability.”
Allen Holub, Holub on Patterns, p. 6.

David Scuse
Department of Computer Science
University of Manitoba

June, 2011

1
2
Chapter 1 Procedural Programming

1 PROCEDURAL PROGRAMMING

1.1 Introduction

In this chapter, we review the basic constructs used to build procedural (no objects) programs.
This chapter includes both Python and Java examples to enable students who were introduced
to procedural programming using the Python language to make the transition to Java. The
programs in these notes were developed using Python version 3.2 and Java version 6.

In the following sections, we develop programs in both Python and Java – these programs are
stored in source-code files; although Python statements may also be entered at a Python
command prompt; we will not take advantage of this technique.

1.2 Programming

A program is a collection of statements in a programming language. The statements are


executed sequentially, beginning with the first statement and continuing statement by
statement until the last statement in the program is encountered (although control structures
may be used to change the order in which statements are executed). The process of
developing programs is called programming (naturally) and the process of removing errors in
programs is referred to as “debugging”.

In the following sections, we will briefly review the programming constructs used to build
procedural programs and examine how programs can be built from these fairly simple
constructs. The following comment from the book Think Python, How to Think Like a
Computer Scientist provides a good description of the thought processes used while
developing programs:

“The goal of this book is to teach you to think like a computer scientist. This way of
thinking combines some of the best features of mathematics, engineering, and natural
science. Like mathematicians, computer scientists use formal languages to denote
ideas (specifically computations). Like engineers, they design things, assembling
components into systems and evaluating tradeoffs among alternatives. Like scientists,
they observe the behavior of complex systems, form hypotheses, and test predictions.

The single most important skill for a computer scientist is problem solving. Problem
solving means the ability to formulate problems, think creatively about solutions, and
express a solution clearly and accurately. As it turns out, the process of learning to
program is an excellent opportunity to practice problem-solving skills.”
Allen Downey, Think Python, pp. 1.
http://greenteapress.com/thinkpython

3 1.2 Programming
Chapter 1 Procedural Programming

1.3 Hello World

The “Hello World” program is the program that is most frequently used to illustrate a new
programming language. Hello World is an important program not only because it provides a
starting point when learning a new language but also because it ensures that the necessary
infrastructure (compiler, paths to libraries, etc.) is set up correctly. The following Python
program prints Hello World!.

print("Hello World!")

In these notes, the output from most programs or program segments is shown directly after the
program. So the program above generates the output:

Hello World!

If any error messages are generated as the program is executed, the error messages are
displayed for the programmer. The following program generates an error because the
statement printer is not defined in Python.

printer("Hello World!")

Traceback (most recent call last):


File "C:\HelloWorld.py", line 1, in <module> printer("Hello World!")
NameError: name 'printer' is not defined

The following Java method prints Hello World!. Note that Java statements must be
terminated by a semi-colon (;):

public static void main(String[] parms)


{
System.out.println("Hello World!");
}

However, this method is not a complete Java program; Java methods must be defined within a
class before they can be compiled and executed correctly. The following program defines a
class named HelloWorld that is placed around the method. By convention, the first letter of
the name of each Java class is defined in upper case. Note that in Java, the name of the class
must be the same as the name of the file in which the class is defined. So the program below
would be defined in a file named HelloWorld.java.

public class HelloWorld


{
public static void main(String[] parms)
{
System.out.println("Hello World!");
}
}

4 1.3 Hello World


Chapter 1 Procedural Programming

Java uses a two-step process in which a program is first compiled and then, if there are no
compilation errors, the program can be executed. The compilation and the execution are
separate steps so two commands must be issued to compile and execute a Java program.
When a Java source file is compiled, Java creates a corresponding file called a “class” file (in
the same directory as the source file). If the source file is named HelloWorld.java, the class
file will be named HelloWorld.class. The class file is used when the program is executed.

In these notes, all programs are run using the (Windows) TextPad environment; if you are
using a different system, your output may be displayed in a slightly different manner. As can
be seen from the following TextPad Tools menu, a Java program is first compiled using
Ctrl+1 and is then executed using Ctrl+2. The Python tool was manually added to TextPad
so depending on how you configured Python, the Python entry is not necessarily in the
TextPad Tools menu, or, if it is, it is not necessary Tool 3.

1.4 Comments

The Python language uses the # character to mark the beginning of a comment. All characters
on the current line that follow the # character are ignored by Python.

# This is my first Python program

print("Hello World!")

The Java language supports two types of comments – the single-line comment that begins
with // and a multiline comment that is surrounded by the characters /* and */

// This is my first Java program


public class HelloWorld
{
public static void main(String[] parms)
{
System.out.println("Hello World!");
}
}

5 1.4 Comments
Chapter 1 Procedural Programming

/*
This is my first Java program
*/

public class HelloWorld


{
public static void main(String[] parms)
{
System.out.println("Hello World!");
}
}

1.5 Assignment Statement

The assignment statement is one of the fundamental constructs in programming languages. It


is used to assign a value to a variable. A variable in Python is a name that begins with an
alphabetic character and is not one of the Python reserved keywords. A variable in Java
follows the same rules (except that the variable must not be the same as one of the Java
reserved keywords).

The following Python program assigns the integer value 25 to the variable i. The program
then prints the value of i. (Again, remember that the output of the program is shown after the
program – the line that contains 25 is the output of the program, not part of the program.)

i = 25
print(i)

25

The two Python statements do not contain a statement terminator. However, the semi-colon
(;) is used in Python as a statement delimiter (when more than one Python statement is on the
same line); so the following Python program is equivalent to the one above.)

i = 25; print(i)

25

In Java, the equivalent statements are:

int i;
i = 25;
System.out.println(i);

Again, unlike Python, Java statements must be defined within a method which is defined
within a class. So the complete Java program is:

public class Program1


{
public static void main(String[] parms)

6 1.5 Assignment Statement


Chapter 1 Procedural Programming

{
int i;
i = 25;
System.out.println(i);
}
}

25

In the remainder of this chapter, we will not include the Java method declarations or Java
class declarations unless it is helpful to do so.

In addition to the method and class information that must be defined in a Java program, the
Java program above also includes the statement

int i;

This statement declares the variable/identifier i to be of type int. The data type int is
common to both Python and Java; the difference is that in Python, variables are not declared
before they are used; in Java, variables must be declared before they are used. Also, in Java,
variables declared to be of a specific type may only be assigned values of that type; in Python,
since variables are not declared to be of a specific type, they may be assigned a value of any
type (this is referred to as “dynamic typing”).

Variables in both Python and Java are case sensitive which means that the variable apple is
not the same variable as Apple.

The arithmetic operators that manipulate integers in Python are the same as those in Java:

Python Java Meaning


+ + addition
- - subtraction
* * multiplication
// (Python 3) / integer (truncating) division
/ (must cast to a real value) real division
% % modulo division (remainder)
** Math.pow(base,exponent) exponentiation

Arithmetic expressions are formed in the same manner in both languages. The following
arithmetic expressions are the same in both Python and Java. Parentheses may be used to
force the order of the evaluation of expressions.

2 + 3
(4 * 5) + 10
(25 - 3) * (-10 +100)

7 1.5 Assignment Statement


Chapter 1 Procedural Programming

Both Python and Java support shortcuts when performing some of the basic assignment
operations.

Python Java Meaning


NA i++ i = i + 1
NA i-- i = i - 1
i += j i += j i = i + j
i -= j i -= j i = i - j
i *= j i *= j i = i * j
i //= j i /= j i = i / j

We will examine data types in more detail later in this chapter but for now, we will work with
simple integers.

1.6 Conditional Execution

In Python, conditional execution is defined with an if statement. Indentation is used to


indicate that one or more statements (a “suite” in Python terms) are within the true portion of
the if statement or within the false/else portion of the if statement. Note that there is a colon :
at the end of the if header and also at the end of the else header.

i = 2
if i > 0:
print(i, "is greater than zero")
else:
print(i, "is not greater than zero")

2 is greater than zero

In Java, conditional execution is similar but requires different delimiters: curly brackets { and
} are used indicate that statements are within the true portion of the if statement or within the
false portion. The indentation of statements within the curly brackets is a programming
convention but is not strictly necessary.

int i;
i = 2;
if (i > 0)
{
System.out.println(i +" is greater than zero");
}
else
{
System.out.println(i +" is not greater than zero");
}

2 is greater than zero

Note that the Java println statement does not add a blank character between parameters; if a

8 1.6 Conditional Execution


Chapter 1 Procedural Programming

blank is required, it must be included by the programmer.

In Python, multiple statements may be included inside the true portion of an if statement
and/or inside the false/else portion of an if statement. Indentation is used to indicate that
statements are contained within the true portion or the false portion of the if statement.

i = 2
if i > 0:
print(i, end=" ")
print("is greater than zero")
else:
print(i, end=" ")
print("is not greater than zero")

2 is greater than zero

In Python, the print function causes a newline character to be generated after the last
character is printed unless the parameter end=" " is included at the end of the parameter list.

In Java, the statements are very similar. Multiple statements may be included within the curly
brackets that enclose the true portion and/or the false/else portion of the if statement.

int i;
i = 2;
if (i > 0)
{
System.out.print(i);
System.out.println(" is greater than zero");
}
else
{
System.out.print(i);
System.out.println(" is not greater than zero");
}

In Java, the print statement does not generate a newline character at the end of the characters
that are printed, while the println statement does generate a newline character at the end of
the printed characters.

The logical expression (or Boolean expression) in the if statement is an expression that
evaluates to either true or false. In the programs above, a simple logical expression that
compares integer values illustrates the use of the numeric comparison operators.

The numeric comparison operators in Python are the same as those in Java:

Python Java Meaning


== == equal
!= != not equal
< < less than

9 1.6 Conditional Execution


Chapter 1 Procedural Programming

> > greater than


<= <= less than or equal
>= >= greater than or equal

More complex logical expressions can be created by including logical operators that join
numeric (relational) expressions.

The logical operators in Python use the name of the operator while those in Java use symbols:

Python Java Meaning


and && and
or || or
not ! not

The result of evaluating a logical expression is a Boolean value (see the Section: Data Types):

Python Java Meaning


True true true
False false false

Python supports some shortcuts when defining logical expressions. For example, the
expression below is a valid Python expression.

3 <= i <= 12

The expression above is not valid in Java but the statement below is equivalent and is also
valid in Python:

(3 <= i) && (i <= 12)

At times it is necessary to have more than 2 conditions. Python supports this with the elif
statement.

i = 2
if i > 0:
print(i, "is a positive number")
elif i < 0:
print(i, "is a negative number")
else:
print(i, "is zero")

2 is a positive number

There may be any number of elif statements and the else statement is optional.

Java does not support the elif statement; instead, additional if statements are used.

10 1.6 Conditional Execution


Chapter 1 Procedural Programming

int i;
i = 2;
if (i > 0)
{
System.out.println(i +" is a positive number");
}
else if (i < 0)
{
System.out.println(i +" is a negative number");
}
else
{
System.out.println(i +" is equal to zero");
}

2 is a positive number

if statements may be nested within other control structures (such as if statements). Again,
the indentation of the statements in Python is important.

i = -20000000
if i > 0:
if i > 1000000:
print(i, "is a big positive number")
else:
print(i, "is a positive number")
elif i < 0:
if i < -1000000:
print(i, "is a big negative number")
else:
print(i, "is a negative number")
else:
print(i, "is zero")

-20000000 is a big negative number

In Java, if statements may also be nested within other control structures.

i = -20000000;
if (i > 0)
{
if (i > 1000000)
{
System.out.println(i +" is a big positive number");
}
else
{
System.out.println(i +" is a positive number");
}
}
else if (i < 0)
{
if (i < -1000000)
{
System.out.println(i +" is a big negative number");
}
else
{

11 1.6 Conditional Execution


Chapter 1 Procedural Programming

System.out.println(i +" is a negative number");


}
}
else
{
System.out.println(i +" is equal to zero");
}

-20000000 is a big negative number

1.7 Loops

A loop is a control structure that causes the statements inside the loop to be executed a
specified number of times. For example, the following Python loop causes the print
statement inside the loop to be executed 5 times, with the variable i being assigned the values
0, 1, 2, 3,and 4. Again, note that the for statement header is terminated with a colon.

for i in range(0, 5):


print(i)

0
1
2
3
4

The corresponding program in Java is very similar.

int i;
for (i=0; i<5; i++)
{
System.out.println(i);
}

Both languages also support a while loop.

# Python while loop


i = 0
while i < 5:
print(i)
i += 1

// Java while loop


i = 0;
while (i < 5)
{
System.out.println(i);
i += 1; // or i++;
}

In Python, if a loop may terminate before all of the values in the for statement are exhausted,
the loop must be written using a while statement. The following program is to print all
values beginning with n and continuing until a value that is a multiple of 20 is found. If such

12 1.7 Loops
Chapter 1 Procedural Programming

a value is found, the loop is to terminate without printing any additional values.

n = 25
i = n
stop = 0
while (i < 50) and (stop==0):
print(i, end=" ")
if ((i//20)*20)==i:
stop = 1
i += 1
print()

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

Although Python (and Java) supports a break statement that permits the programmer to exit
from a loop at any time, using a break statement is a poor programming practice and it will
not be used in these notes.

In Java, the for statement supports the addition of extra clauses that determine when the loop
is to terminate so it is not necessary to write the loop using a while statement.

int n;
int i;
int stop;

n = 25;
stop = 0;
for (i=n; (i<50)&&(stop==0); i++)
{
System.out.print(i +" ");
if ((i/20*20)==i)
{
stop = 1;
}
}
System.out.println();

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

Both Python and Java support control structures nested within other control structures so it is
valid to have a loop within a loop.

1.8 Functions/Methods

Python and Java both support functions that are very similar in appearance. In Python, the
function is declared before it is referred to. The definition of a function may include any
number of parameters passed from the calling function.

The following Python program shows how a function that prints the integer values from 0 to
(n-1) is defined and then called from the main function.

13 1.8 Functions/Methods
Chapter 1 Procedural Programming

def print_loop(n):
for i in range(0, n):
print(i)
return

print_loop(5)

If a function does not return a value, it is often referred to as a “void function”. A void
function may include a return statement that does not include a return value; however, the
return statement is not required.

In Java, functions are referred to as “methods”. For now, all Java methods will be specified
with the keyword static. The type of value returned by a method is either void (meaning
the method does not return a value) or a valid Java data type (such as int). A void method in
Java is the same as a Python void function – both may include a return statement that does
not specify a value to be returned. In the following example, the class definition is included
around the two methods.

public class FunctionTest


{
public static void main(String[] parms)
{
print_loop(5);
}

public static void print_loop(int n)


{
int i;

for (i=0; i<n; i++)


{
System.out.println(i);
}
}
}

In Java, a method may be defined either before or after it is referred to.

1.9 Lists/Arrays

An array is a programming construct that can store a collection of values. In Python, the more
generic term “collection” is used instead of array. Python has different types of collections
but we will focus on the “list” collection in this chapter. The following Python statement
creates a Python list that contains the integer values 1, 2, 3, and 4.

my_list = [1, 2, 3, 4]

The advantage of using a list (instead of individual integer values) is that the collection may
be passed to a function by specifying only the name of the list (instead of having to pass all of

14 1.9 Lists/Arrays
Chapter 1 Procedural Programming

the values individually).

The following Python program creates a list and then passes the list to the function
print_list which prints the elements of the list on the same line.

def print_list(my_list):
for i in range(0, len(my_list)):
print(my_list[i], end=" ")
print()
return

my_list = [1, 2, 3, 4]
print_list(my_list)

1 2 3 4

Python lists are “zero-based” (or “0-based”), meaning that the first element in the list is
element zero and is accessed by my_list[0] in the program above. The variable i in the
program above is used as a “subscript” – a value that specifies the position of an element in a
list that is to be accessed.

Python provides a variation of the for statement that makes the manipulation of lists easier.
The version below uses the modified for statement that specifies that the variable i is to be
assigned one value from the list each time through the loop. In this program, the variable i is
no longer a subscript, i contains an element of the list.

def print_list(my_list):
for i in my_list:
print(i, end=" ")
print()
return

The following Java methods illustrate the statements required to initialize a Java array and
then print the contents of the array using a Java method.

public static void main(String[] parms)


{
int[] my_list;
my_list = new int[] {1, 2, 3, 4};
print_list(my_list);
}

public static void print_list(int[] my_list)


{
int i;

for (i=0; i<my_list.length; i++)


{
System.out.print(my_list[i] +" ");
}
System.out.println();
}

1 2 3 4

15 1.9 Lists/Arrays
Chapter 1 Procedural Programming

As can be seen, Java requires more effort to declare the array, to pass the array as a parameter,
and to manipulate the array, but the structure of the program is very similar to the structure of
the Python program.

An array variable is declared in Java by placing square brackets [ and ] after the data type
that the array is to contain. The parameter of the print_list function must be declared to be
of the desired type, in this case, an integer array int[]. The number of elements in the array
is determined in a manner similar to that of Python; in Python, len(my_list) is used while in
Java, my_list.length is used.

Lists/arrays can be modified in both Python and Java but Python provides signiciantly more
flexibility than does Java.

The following Python program creates a new list and initializes the elements to the values 0,
1, 2, …, n-1 where n is passed as a parameter to the create_list function.

def print_list(my_list):
for i in my_list:
print(i, end=" ")
print()
return

def create_list(n):
my_list = []
for i in range(0, n):
my_list.append(i)
return my_list

my_list = create_list(5)
print_list(my_list)

0 1 2 3 4

The statement my_list = [] is used to create a new, empty list. The Python append function
is used to append an element to the end of an existing list. So the effect of this program is to
create a list that consists of the values 0, 1, 2, 3, 4 and then print that list.

The equivalent Java program is shown below.


public static void main(String[] parms)
{
int[] my_list;

my_list = create_list(5);
print_list(my_list);
}

public static int[] create_list(int n)


{
int[] list;
int i;

16 1.9 Lists/Arrays
Chapter 1 Procedural Programming

list = new int[n];


for (i=0; i<n; i++)
{
list[i] = i;
}
return list;
}

public static void print_list(int[] list)


{
int i;

for (i=0; i<list.length; i++)


{
System.out.print(list[i] +" ");
}
System.out.println();
}

0 1 2 3 4

Although the two programs are very similar (ignoring the syntactic differences), there is one
significant difference. In Python, a list is a dynamic structure: a list is typically created as an
empty list and then elements are added to the end of the list using the append function. In
Java, an array is a static structure: it is given an initial size and this size can not be modified.
Once a Java array has been created, the elements of the array are modified by replacing their
initial values. In the Java program above, the array is declared to be of size n (which is 5 in
this example). At this point, the array contains 5 elements (which are initialized to zero by
Java). Any of these 5 elements may be modified using an assignment statement such as:
list[3] = 4; However, the size of the array is set to 5 and this can not be changed.

The following function illustrates how the maximum value in a Python list can be determined.
def max_list(my_list):
max = my_list[0]
for i in my_list:
if i > max:
max = i
return max

The program does have some warts in it – if the list is empty, the program terminates
abnormally; also, the first element in the list is processed twice. However, these problems can
be fixed with a little effort.

The equivalent Java method is shown below.


public static int max_list(int[] my_list)
{
int max;
int i;

max = my_list[0];
for (i=1; i<my_list.length; i++)

17 1.9 Lists/Arrays
Chapter 1 Procedural Programming

{
if (my_list[i] > max)
{
max = my_list[i];
}
}
return max;
}

Python contains functions that permit the programmer to insert a new element at any location
in an existing list, delete an element from a list, and append to the end of a list. These
functions do not exist with arrays in Java but can be written by the programmer. The
following Java method remove_element removes an element from an existing array
(assuming that the element exists in the array). It is important to note that the parameter
passed to remove_element is the value of the element to be deleted, not the position of the
element to be deleted. The method System.arraycopy is described in more detail in the next
chapter.
public static void main(String[] parms)
{
int[] my_list;

my_list = create_list(5);
print_list(my_list);
System.out.println();

my_list = remove_element(my_list, 0);


print_list(my_list);

my_list = remove_element(my_list, 1);


print_list(my_list);

my_list = remove_element(my_list, 4);


print_list(my_list);

my_list = remove_element(my_list, 3);


print_list(my_list);
}

public static int[] create_list(int n)


{
int[] list;
int i;

list = new int[n];


for (i=0; i<n; i++)
{
list[i] = i;
}
return list;
}

public static int[] remove_element(int[] list, int element)


{
int[] new_list;
int position;
int i;

18 1.9 Lists/Arrays
Chapter 1 Procedural Programming

position = -1;
for (i=0; i<list.length; i++)
{
if (list[i] == element)
{
position = i;
}
}
if (position == -1)
{
new_list = list; // the element was not found, so return the original list
}
else
{
new_list = new int[list.length-1];
System.arraycopy(list, 0, new_list, 0, position);
System.arraycopy(list, position+1, new_list, position, new_list.length-position);
}
return new_list;
}

public static void print_list(int[] list)


{
int i;

for (i=0; i<list.length; i++)


{
System.out.print(list[i] +" ");
}
System.out.println();
}

0 1 2 3 4

1 2 3 4
2 3 4
2 3
2

As can be seen, deleting an element from an array is not a trivial exercise. However, Java
does contain a more sophisticated collection mechanism which is discussed in Chapter 9 –
Object Collections.

1.10 Passing Parameters

Parameters of functions are treated in essentially the same manner in both Python and Java. If
a numeric value is passed to a function, the value may be modified within the function but the
modified value does not replace the original value in the calling function. In the following
example, the value of n is passed to function1. n is modified within the function but this
modified value does not replace the original value of n in the calling function when
function1 returns.

19 1.10 Passing Parameters


Chapter 1 Procedural Programming

def function1(n):
print(n)
n += 1
print(n)
return

n = 10;
function1(n)
print(n)

10
11
10

Java works in exactly the same manner. Numeric values that are passed to a method may be
modified in the method but the modifications are not visible in the calling method.

In Python, if a list is passed to a function and an element of the list is modified in the function,
the modification is reflected back (or is visible) in the calling function. In the following
example, the third element of list is modified in function2. As can be seen in the output,
this modification is visible in the calling function.

def function2(list):
print(list)
list[2] += 10
print(list)
return

list = [1, 2, 3, 4]
function2(list) # list is updated by function call
print(list)

[1, 2, 3, 4]
[1, 2, 13, 4]
[1, 2, 13, 4]

In Java, the elements of an array may be modified in a method call and the changes are visible
in the calling method.

In Python, if the number of elements in a list is modified in a function (for example, by


appending a new element to the end of the list), the change is visible in the calling function.
If this operation is performed in a Java method, the changes are not visible in the calling
method. The following Java program illustrates this issue.

public static void main(String[] parms)


{
int[] my_list;
my_list = new int[] {1, 2, 3, 4, 5};
print_list(my_list);
add_element(my_list, 200);
print_list(my_list);
}

20 1.10 Passing Parameters


Chapter 1 Procedural Programming

public static void add_element(int[] my_list, int element)


{
int[] new_list;

new_list = new int[my_list.length+1];


System.arraycopy(my_list, 0, new_list, 0, my_list.length);
new_list[new_list.length-1] = element;
my_list = new_list;
print_list(my_list);
}

public static void print_list(int[] my_list)


{
int i;

for (i=0; i<my_list.length; i++)


{
System.out.print(my_list[i] +" ");
}
System.out.println();
}

1 2 3 4 5
1 2 3 4 5 200
1 2 3 4 5

In Java, if the size of an array in the calling method must be modified, the called method must
return the modified array and the calling method must assign the modified array to the
original array.

public static void main(String[] parms)


{
int[] my_list;
my_list = new int[] {1, 2, 3, 4, 5};
print_list(my_list);

my_list = add_element(my_list, 200);


print_list(my_list);
}

public static int[] add_element(int[] my_list, int element)


{
int[] new_list;

new_list = new int[my_list.length+1];


System.arraycopy(my_list, 0, new_list, 0, my_list.length);
new_list[new_list.length-1] = element;
my_list = new_list;
print_list(my_list);
return my_list;
}

public static void print_list(int[] my_list)


{
int i;

for (i=0; i<my_list.length; i++)


{
System.out.print(my_list[i] +" ");
}
System.out.println();

21 1.10 Passing Parameters


Chapter 1 Procedural Programming

1 2 3 4 5
1 2 3 4 5 200
1 2 3 4 5 200

Python supports keyword parameters but since this type of parameter is not supported in Java,
they will not be examined in these notes.

1.11 Scope

The scope of variables in Python is straightforward – variables used in a function are local to
that function. When the function terminates, the variables are destroyed. If a variable in a
calling function is required in a called function, the variable should be passed to the called
function as a parameter. The value of the variable can then be accessed without any
problems. Depending on the type of the variable, it may also be possible to modify the
variable in the called function and have the modification visible in the calling function (see
the previous Section: Passing Parameters).

Python permits variables that are given values in the calling function to be accessed (but not
modified) in a called function (without passing the variables as parameters). We will not
examine this technique since it is not a standard programming construct.

In Java, variables are local to the method in which they are declared. Java does not permit
variables that are declared in one method to be accessed in a called method. So, if the value
of a variable in a calling method is required in a called method, the variable must be passed to
the called method.

1.12 Data Types

Java implements a collection of data types that are referred to as “primitive data types”. As
we shall see later in these notes, the primitive data types are stored in a different manner than
non-primitive data types (which are objects). Java’s primitive data types are: byte, short,
int, long, float, double, char, and boolean. Each variable declared in a Java program
is given a specific type. The types byte, short, int, and long are used to represent integer
values of varying sizes. The types float and double are used to represent floating-point
values of different sizes. The type boolean is used to store a Boolean value (true or false).
The type char is used to store a single character. A variable that is given one type can not be
assigned a value of another type (unless the two types are compatiable or some additional
work is performed).

Java’s primitive data types are shown below. Python does not have “primitive data types” but
it does have some core data types that are similar to Java’s primitive data types.

22 1.12 Data Types


Chapter 1 Procedural Programming

Python Java Meaning


int an integer of any size
byte -128 <= integer <= 127
short -32768 <= integer <= 32767
int -2147483648 <= integer <= 2147483647
long approximately 18-digit integer
float floating-point value with 7-digit accuracy
float double floating-point value with 15-digit accuracy
bool boolean Boolean (true/false)
char one character

Python uses dynamic typing for its variables. This means that Python variables are not
declared to have a specific type; instead, when a Python variable is assigned a value, the type
of the value is stored with the actual value. So it is perfectly valid in Python to assign an
integer value to a variable, use the variable in statements that make sense for integers, and
then at a later time, assign a boolean value to the variable. As long as the variable is then
used in a boolean context, the program will work correctly.

Python permits the programmer to determine the type of the value currently stored in a
variable using the type() function (remember that a variable does not have a type in Python).

i = 25;
j = 25.5
print(type(i))
print(type(j))

<class 'int'>
<class 'float'>

To make the type output slightly nicer, the following function get_type can be used. (The _ _
used in the function is 2 underscore characters typed side-by-side.)

def get_type (var):


return var.__class__.__name__

i = 25
j = 25.5
print(get_type(i))
print(get_type(j))

int
float

If it is necessary to convert a value from one type to another, Python provides a collection of
functions to perform the conversion. The int() function converts its parameter to an integer
value; the float() function converts its parameter to a floating-point value.

23 1.12 Data Types


Chapter 1 Procedural Programming

The following statements illustrate the conversion between the integer and floating-point data
types in Python.

i = 25;
print(i)
j = float(i)
j += 0.5
print(j)
i = int(j)
print(i)

25
25.5
25

In Java, data types are converted from one type to another using Java’s “cast” mechanism. A
cast involves placing the desired type in parentheses before an expression or variable. The
following Java statements have the same effect as in the Python statements above.

int i;
float j;

i = 25;
System.out.println(i);
j = (float) i;
j += 0.5;
System.out.println(j);
i = (int) j;
System.out.println(i);

25
25.5
25

1.13 Strings

Python supports the data type str which is used to store a collection of characters (or a
character string). The following statements illustrate the use of character strings in Python.

s = "abc"
print(s)
print(type(s))

abc
<class 'str'>

In Python, strings may be delimited either by single quote marks (') or by double quote
marks ("). As long as a string begins and ends with the same delimiter, it doesn’t matter
which is used.

The type conversion functions in Python can be used to convert between numeric values and
strings. For example, the statements illustrate the conversions between an integer and a

24 1.13 Strings
Chapter 1 Procedural Programming

string.

i = int("123")
s = str(i)

A subset of the contents of a string can be extracted using the square brackets notation (this is
referred to as “slicing” in Python). The following example illustrates this process.

s = "abc"
t = s[1:2]
print(t)

The notation [from, to] means that the characters beginning with character from and
continuing up to but not including character to are extracted. As with arrays, character
indexing is zero-based. If only the from value is included, only the one corresponding
character is extracted. If the notation [from:] is used, this means extract characters
beginning at the from character and continuing until the end of the string. (The slicing
notation supported in Python contains additional options that we will not examine.)

Strings in Python are compared using the relational operators ( <, >, ==, etc.) When strings
are compared for equality in Python, it is important that the == operator be used. As we shall
see, this is not the case in Java.

Python contains a rich collection of functions that manipulate character strings. For more
information, take a look at the web or a Python textbook.

Java supports the primitive data type char which can be used to store one character. If you
want to store a collection of characters (or a character string) in Java, you could use a char[]
(array) but a more convenient mechanism for manipulating character strings in Java is the
data type String (which is not a primitive data type).

String s;

s = "abc";
System.out.println(s);

abc

Java also permits the programmer to extract a subset of the characters in a character string.
However, in Java, a method named substring is used to perform the processing. The
parameters of substring are almost the same as Python’s slicing notation. The only
difference is that in Java, if only one value is supplied, all characters beginning at that
position and continuing until the end of the string are extracted.

25 1.13 Strings
Chapter 1 Procedural Programming

String s;
String t;

s = "abc";
System.out.println(s);
System.out.println(s.substring(1,2));
System.out.println(s.substring(1));

abc
b
bc

In Java, when two strings are compared for equality, a special method, the equals method,
must be used instead of the relational operator ==.

String s;
String t;

s = "abc";
t = "abc";
if (t.equals(s))
{
System.out.println("The strings are equal");
}
else
{
System.out.println("The strings are not equal");
}

1.14 Modules/Classes

The statements and functions defined inside a Python file (a .py file) are referred to as a
Python module. Python includes many modules that provide useful functionality (so that the
programmer does not have to write all of the functions him/herself). A simple example is the
math module that contains many mathematical functions. Before the functions in a module
may be used, the module must be made available (imported).

import math

i = math.sqrt(25.0)
print(i)

5.0

Java also contains a variety of predefined methods and its equivalent of modules. For
example, the mathematical functions are also collected together into a Math “class”. This
class can be imported using the statement shown at the beginning of the following program.
To make life a little easier for the programmer, Java automatically imports the Math class
(along with a variety of other classes) so the import statement below is not actually
necessary.

26 1.14 Modules/Classes
Chapter 1 Procedural Programming

import java.lang.Math;

public class TestModules


{
public static void main(String[] parms)
{
double d;

d = Math.sqrt(25.0);
System.out.println(d);
}
}

5.0

1.15 Determining Prime Numbers

The following program determines the prime numbers that are less than n. A number is prime
if it does not have any integer divisors greater than 1 other than itself.

def isPrime(value):
result = True
count = 2
while (count<value) and (result):
if (((value//count)*count)==value):
result = False;
count += 1
return result

def generatePrimes(n):
list = []
for i in range(2, n):
if isPrime(i):
list.append(i)
return list

list = generatePrimes(40)
print(list)

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]

The corresponding Java program is shown below.

public class Primes


{
public static void main(String[] parms)
{
int[] list;

list = generatePrimes(40);
print_list(list);
}

public static int[] generatePrimes(int max)


{
int[] list;
int[] new_list;
int numPrimes;
int count;

27 1.15 Determining Prime Numbers


Chapter 1 Procedural Programming

list = new int[max];


numPrimes = 0;
for (count=2; count<max; count++)
{
if (isPrime(count))
{
list[numPrimes] = count;
numPrimes++;
}
}

new_list = new int[numPrimes];


System.arraycopy(list, 0, new_list, 0, numPrimes);
return new_list;
}

public static boolean isPrime(int value)


{
int count;
int sqrt;
boolean result;

result = true;
for (count=2; (count<value) && result; count++)
{
if (((value/count)*count)==value)
{
result = false;
}
}
return result;
}

public static void print_list(int[] my_list)


{
int i;

for (i=0; i<my_list.length; i++)


{
System.out.print(my_list[i] +" ");
}
System.out.println();
}
}

2 3 5 7 11 13 17 19 23 29 31 37

As can be seen, the Java program is more “wordy” than the Python program although the Java
program does not require more thought than the Python program (with the possible exception
of shrinking the array of primes to the exact size needed).

The prime number generation programs are presented without any discussion of how such
programs would be developed. The process of developing programs is discussed in the next
Chapter.

28 1.15 Determining Prime Numbers


Chapter 1 Procedural Programming

1.16 Differences between Python 2 and Python 3

The print function has been added to Python 3; in Python 2, print was a statement that did
not require parentheses.

print 1, 2, 3 # Python 2
print(1, 2, 3) # Python 3

There have also been some changes to the way that integers are defined and manipulated.

long # Python 2: the long type was removed in Python 3


a / b # Python 2: integer result
a / b # Python 3: real (floating point) result
a // b # Python 3: integer result

1.17 Differences between Python and Java

Java uses brace/curly brackets to start and end blocks, while Python uses indentation.

Java employs static typing, while Python is dynamically typed.

Java methods are explicitly declared to be static.

Java uses array.length while Python uses len(list).

There are several types of integer values in Java (depending on the maximum integer to be
manipulated); Python only has one type which can manipulate integers of any size.

The representation of Python data values is different from the representation of Java values,
particularly Java primitive data types.

1.18 Summary

In this chapter, we examined the fundamental constructs used in procedural programming.


This chapter has only scratched the surface of the Python language – Python contains many
elegant constructs and also some very powerful libraries of predefined functions.

29 1.18 Summary
Chapter 1 Procedural Programming

30 1.18 Summary
Chapter 2 Growing Algorithms

2 GROWING ALGORITHMS

2.1 Introduction

In this chapter, we introduce the process of “growing” software, that is, instead of writing an
entire program at once, the program is grown incrementally from a small, working portion of
code, adding functionality in small pieces until the desired result is achieved. This process is
also known as iterative development.

2.2 Searching a List

Searching the elements in a list for a specific element is one of the standard computer science
algorithms and is used in a wide variety of programs. In the following example, an array of
integers is searched for a specific integer. We begin by defining a simple main method that
indicates the parts of the program that must be defined. We will use this program
organization throughout these notes – the main method will not perform any explicit
processing; instead, it will call appropriate methods that perform the processing.

public static void main(String[] parms)


{
int[] list;
int searchValue = 10;
int result;

list = createList();
result = searchList(list, searchValue);
System.out.println("Result is: " +result);
}

The main method shown above defines the structure of the program that is to be created. A
method “createList” is used to initialize the array of integers and a method “searchList” is
used to examine the elements in the array of integers, looking for an element that is identical
to the value in “searchValue”. By defining the main method in this manner, we have reduced
the problem to smaller components and we can now examine these components individually.

We need a method createList that stores a collection of integer values in an array and returns
the array to the main program. Following our rule of doing the simplest thing that could
work, the createList method is initially defined with a “hard coded” array of integers. (Hard
coding means that the values are specified in the program instead of being supplied by the
user or read from a file.)

public static int[] createList()


{
int[] list = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};

return list;
}

31 2.2 Searching a List


Chapter 2 Growing Algorithms

Note that since createList returns an array of integers, its return type must be declared as int[]
instead of void. While this version of createList is quite limited, it does provide a working
version that can be improved upon later. A method that works correctly but is not complete is
often referred to as a “stub” method.

Now, we need a searchList method that accepts the array and a simple integer value and
determines whether or not the integer is an element of the array. The searchList method is
initially created to return 0, the position of the first element in the array.

public static int searchList(int[] list, int searchValue)


{
int result;

result = 0;
return result;
}

At this point, the program actually works correctly – it creates an array of integers and
identifies the position of the integer that is being searched for in the array. While the program
works only for the array that is hard coded in the createList method, the program does identify
all of the necessary components. By first breaking the program down into smaller pieces and
writing very simple instructions that work (in a very limited manner), we can now concentrate
on improving the individual methods one-at-a-time.

Of course, if you know exactly what is required in each method, it is not necessary to grow
the program so slowly; instead, you can take bigger steps towards the solution. However, the
advantage of developing a program slowly is that if something goes wrong between one
iteration and the next, it is easier to identify the cause of the problem.

The goal of approaching program development in this manner is to ensure that the overall
design of the program is correct before adding the details. The design of a program is similar
to the blueprint of a building that is to be constructed. However, there are significant
differences between developing software and building (or engineering) a physical structure –
these issues will be addressed from time to time in these notes.

Now we improve the methods so that each becomes more general.

We initially hard coded the array in the createList method.

32 2.2 Searching a List


Chapter 2 Growing Algorithms

public static int[] createList()


{
int[] list;

list = new int[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
return list;
}

An alternative is to generate random values using the Math.random method.

public static int[] createList()


{
int[] list;
int count;
int numElements = 10;

list = new int[numElements];


for (count=0; count<numElements; count++)
{
list[count] = (int) (Math.random()*101.0);
}
return list;
}

The array is constructed to contain 10 random integer values in the range 0 to 100. (Recall
that Math.random returns a double value (in the range: 0 ≤ value < 1) so the random value
must be cast to an int before it can be stored in the array.) This version is a definite
improvement over the previous version but we will see that other versions of createList can
also be defined.

2.2.1 Linear Search

In our initial version of searchList, we simply returned the position of the first element in the
array. This allowed us to get the program working but this method now must be improved so
that it works correctly with all data.

public static int searchList(int[] list, int searchValue)


{
int result;

result = 0;
return result;
}

33 2.2 Searching a List


Chapter 2 Growing Algorithms

A simple linear search of the elements in the array can be used to locate the value.

public static int searchList(int[] list, int searchValue)


{
int count;
int result;

result = -1;
for (count=0; count<list.length; count++)
{
if (list[count] == searchValue)
{
result = count;
}
}
return result;
}

The searchList method now returns the location of the desired element in the array if the
element is found or returns -1 if the element is not found. Returning a value of -1 to
indicate that a method was not able to accomplish its task is a common technique.

In the method above, the loop continues until the end of the array even if the desired element
is located. While we are not going to attempt to optimize each program as much as is
possible, this is an example that is particularly easy to improve by modifying only the loop
condition so that the loop terminates as soon as the desired element is located.

public static int searchList(int[] list, int searchValue)


{
int count;
int result;

result = -1;
for (count=0; result==-1 && count<list.length; count++)
{
if (list[count] == searchValue)
{
result = count;
}
}
return result;
}

Now the loop continues as long as the desired value has not been located and there are still
more elements to be examined in the array.

If data are to be provided by a user, the createList method becomes somewhat more complex.
JOptionPane can be used to obtain each value from the user, but we don’t know in advance
how many elements will be entered. The simplest solution is to ask the user to specify the
number of elements that will be entered. Then, the array can be created so that it is exactly
the right size.

34 2.2 Searching a List


Chapter 2 Growing Algorithms

public static int[] createList()


{
int[] list;
int numElements;
int count;
int value;
String string;

string = JOptionPane.showInputDialog("Please enter the number of values:");


numElements = Integer.parseInt(string);
list = new int[numElements];

for (count=0; count<list.length; count++)


{
string = JOptionPane.showInputDialog("Please enter a number:");
value = Integer.parseInt(string);
list[count] = value;
}
return list;
}

Note that the array was declared at the beginning of the method but the array was not
instantiated (with an = new() statement) until later in the method when the actual number
of elements to be stored in the array was known. This is a common Java programming
technique.

There are other ways in which an unknown number of elements can be stored in an array and
we will examine some of these techniques later in this chapter.

Recall that when Java’s Graphical User Interface (GUI) components are used, the program
must import the GUI component(s) from the Swing package.

import javax.swing.JOptionPane;

Similarly, to ensure that the program terminates correctly when GUI components are used, the
statement below must be included at the end of the main method.

System.exit(0);

Having to type values into the console each time that the program is tested is annoying after
the first couple of iterations. It is often easier to generate random data and then switch to
user-supplied data only when all parts of the program are working.

An alternative to using JOptionPane is to read the data from a (disk) file that is provided by
the user. We will examine how to read information from files in Chapter 4 – File Input and
Output.

35 2.2 Searching a List


Chapter 2 Growing Algorithms

2.2.2 Linear Search of an Ordered List

If an array is sorted into ascending order, then the contents of the array are arranged so that
the value of the first element is less than or equal to the value of the second element, the value
of the second element is less than or equal to the value of the third element, and so on. The
following diagram shows the contents of an array that consists of 5 elements, with each
element less than or equal to all following elements.

We will examine techniques that sort the contents of an array into a particular order in
Chapter 13 – Sorting but for now we will assume that the integers are provided in sorted
order.

If the elements in an array have been sorted into ascending order, there are several ways in
which the array can be searched that make the search process more efficient. Our original
linear search algorithm searches the array until either the desired element is found or until the
end of the array is found.

public static int searchList(int[] list, int searchValue)


{
int count;
int result;

result = -1;
for (count=0; result==-1 && count<list.length; count++)
{
if (list[count] == searchValue)
{
result = count;
}
}
return result;
}

This search process can be improved slightly by stopping the search as soon as the desired
element is found or when an element with a value that is larger than the desired element is
found. The search is still a linear search but it stops earlier if the desired element is not found.

36 2.2 Searching a List


Chapter 2 Growing Algorithms

public static int searchList(int[] list, int searchValue)


{
int count;
int result;

result = -1;
for (count=0; searchValue>=list[count] && result==-1
&& count<list.length; count++)
{
if (list[count] == searchValue)
{
result = count;
}
}
return result;
}

The example works correctly in most cases but has a problem (or bug) in one particular
situation: if the desired element is greater than the largest element in the array, a subscript-
out-of-bounds exception is generated. This problem can be eliminated by reordering the for
condition to ensure that position is still within the array before evaluating the condition
searchValue>=list[count].

It is important to understand why the program above does not work correctly in all situations.
When learning to program, it is much more important to write code that is correct than to be
concerned about efficiency.

The correct version of the program is shown below.

public static int searchList(int[] list, int searchValue)


{
int count;
int result;

result = -1;
for (count=0; result==-1 && count<list.length && searchValue>=list[count]; count++)
{
if (list[count] == searchValue)
{
result = count;
}
}
return result;
}

This example illustrates how easily a bug that occurs only occasionally can be introduced into
a program. Many programmers do not perform sufficient testing of their programs and
problems such as this one may slip through the development process and then cause the
system to crash when the system is put into production.

37 2.2 Searching a List


Exploring the Variety of Random
Documents with Different Content
bright and happy home which she had quitted upon her errand of
love. The brightness of her dark and expressive eyes was contrasted
with the marble whiteness of her complexion, her beautiful hair,
which had formerly graced the most precious pearls, and adorned
costly diamonds, the gifts of royal love, was now confined by a
simple braid, and the form, once decked in imperial purple, and
glittering in courtly magnificence, was now wrapped in the plainest
garb, the simplicity of which could not hid the loveliness of her form.
In a voice of soothing sympathy, she gave some directions to the
sorrowing servants, and then kindly led the bereaved relations from
the chamber of death. “He has departed in peace,” said she, as they
entered a retired chamber, “may our last end be like this; may we die
the death of this righteous man, and now, dearest friends, the swiftly
passing moments warn me to be quick in what I have to relate. Your
minds, I know, are stayed upon the Rock of Ages, and though I
speak of danger and death, ye will know that the Lord of all the earth
will do right. Brother Ambrose, last night, brought the tidings that
tomorrow is appointed for another of those awful scenes with which
Rome is now familiar, and, though we know that the moment when
the soul of the Christian takes its flight from this world of sorrow and
wickedness is a moment which introduces it to an eternity of
happiness, unalloyed and unspeakable, yet we turn with shuddering
grief, from its accompaniments of pain and torture.” “Oh, tell me not,”
said Cleone, with startling agony of voice and manner, “say not that
our Curtius is condemned,” and overcome with grief and terror, she
sank upon the ground, while the mother, with her hands clasped, and
her eyes raised, prayed for strength from above. “He is indeed
condemned,” said Sister Helena, “but listen, dear sisters, and see if
there is not a ray of hope to lighten this gloomy hour. After learning
these tidings, I left our retreat immediately to comfort you, if possible,
and, with hasty steps proceeded along the private path which leads
from our secluded dwelling directly by the remains of the ancient
temple upon the hill. While groping my way through the ivy and thick
bushes, I was startled by the sound of voices, proceeding from the
ruins, and the name of the Emperor repeated with the most awful
threats, and joined to the fear of discovery induced me to stop and
conceal myself. That the speakers were bitter enemies to Nero was
evident from their conversation, and, in a short time I gathered from
it that they had entered into a conspiracy, and bound themselves by
solemn oaths to take his life, and, that the moment of his leaving the
amphitheatre, after the executions, was chosen to effect their
purpose, as being a moment of confusion and dismay. The infamous
Caius Piso, whose inveterate hate for the Emperor is so well known,
I discovered, was at the head of the conspiracy, and their measures
are so well concerted that they must succeed. Now, dear friends,
may we not, by warning Nero of this imminent, this certain danger,
save the life of your beloved Curtius? Listen, Cleone, have you
courage to face this cruel Emperor, and intercede for the life of your
brother? And, if he refuses to grant it to your prayers, yet you may
induce him to mercy by convincing him that the means of saving his
own life is in your power.” “But, do you reflect, Helena, that this
inhuman tyrant may, and most probably would turn a deaf ear to all
her intercessions, and force her, by torture, to confess her
knowledge of this conspiracy? No, it is for me to offer myself a
sacrifice for my son. I will endure every torment he can inflict, and,
perhaps, when convinced that he cannot extort the secret, he will
grant me the life of my child.” “Mother,” said Cleone, throwing her
arms around her neck, “mother, do you doubt my resolution, my
courage, my ability to endure any suffering for the sake of those so
dear to me? Oh, let me go; I will throw myself at his feet; he cannot
resist my supplications; he will be grateful to us for saving him from
sure destruction, and reward us by restoring my brother to his home
and friends.” “Hear me,” said Sister Helena, “I myself would be the
intercessor, were I not certain that Nero would recognize in me one
who has incurred his mostly deadly hatred, one whom he would not
hesitate to sacrifice to his revengeful passions, and whose entreaties
for the life of the young Christian would only be a passport for his
speedy death. You, madam,” said she, addressing the distressed
and almost fainting mother, “are known as a Christian. You have
already been exposed to the suspicions of Nero, and have but barely
escaped his cruel persecutions by a life of the strictest seclusion.
Your daughter, reared in retirement, and unknown to the world,
would not be so obnoxious, and she might not be unprotected. The
young Flavius, the unswerving friend of Curtius, who has already
braved the indignation of the tyrant, for his sake, would, without
doubt, accompany and support her, and high in rank, and beloved by
all parties, his influence would go far to ensure her safety. But, we
have but moments to deliberate; midnight is the time appointed for
these conspirators to meet and perfect their plan, and, if we resort to
these, I am convinced, only means, to save the life of this dear
friend, Nero must know all in season to apprehend them together.”
“Do not hesitate, mother, dearest, dearest mother, let me save my
brother from this awful death; I shall be safe; God will protect me; He
will aid me to confront this terrible Nero.” “My Cleone, my darling
child, must I expose you to this danger? Must I thrust you, as it were,
into the jaws of this inhuman monster? Oh, think, dear sister, of his
aggravated cruelties; remember the fate of his own mother and wife;
when has any consideration stayed his barbarity? How can we
expect, how can we even hope that he will lose his grasp of a victim,
so completely in his power? He will sacrifice them both, and I—I
shall be left childless and alone!” Tears of commiseration streamed
from the eyes of the sympathizing recluse. “Be it as you please,” said
she, “I cannot, dare not urge you to a measure which may indeed
end as you fear; although I think it would be otherwise. I know the
disposition of Nero. Alas!” said she, with shuddering grief, “who
should know it so well! Amidst all his fierce cruelty, he is a very
coward by nature, and nothing so perfectly unmans him as the fear
of death.” “Go then, my Cleone,” said her mother, “if possible, save
your brother from this dreadful doom, and if I am bereaved of both, I
will pray that I, too, may join you in that heaven, where there is no
separation.”

The evening was now advanced, and Herbert closed the volume.
“How was it possible,” said Susan, “that Valeria, for it was she, I
suppose, who bore the name of Sister Helena, could have eluded
the search of the vindicative Emperor? With his exasperated
feelings, he would leave no means untried to discover her, and these
being joined with his great power, I cannot imagine how she could
have been saved.” “Though the early Christians,” said Herbert,
“when called to give a reason for the hope that was in them, were
bold in conscious innocence, though they shrank not from danger or
death in the service of their Master, still, they did not, needlessly,
cast away their lives; but, even with the prudence of worldly wisdom,
avoided exposure. Their residence was often in the most obscure
places, in the depths of gloomy forests, or in caves of the earth, from
whence, in the still hours of night, the sounds of praise and
thanksgiving arose to Him to whom ‘the darkness is as at noonday.’
Many of these subterranean abodes are still shown, and the
inscriptions upon the rugged walls prove them to have been the
homes of the persecuted Christians.” “I should like to go to Rome,”
said Charles, “and go into those caves, and see the ruins of that
great city.” “And those ancient pavements,” said Mary, “which have
been swept by the imperial purple, and visit the tombs, where rest
the remains of those great and good, of whom we read.” “Now Mary
is upon her hobby,” said Susan, “and she will not stop short of the
Holy Land at least. If she were only an old man, with a big wig, she
would be a most inveterate antiquary.” “I will sympathize with you,
dear Mary,” said Elizabeth, “if to read of former ages, and their
stirring events, excites so much interest, how delightful to stand upon
the spots commemorated in history, but, above all, to tread in the
footsteps of the Saviour, and visit the scenes hallowed by his
presence.” “To stand upon the Mount of the Olive trees,” said
Herbert, “to wander by the brook Cedron, and through the ancient
burial places of the Jews. To linger by the shores of the sea of
Galilee, and mark the swelling waters, to fix in our ‘mind’s eye’ the
very place where Jesus walked upon the boisterous waves. Come
evening, remind me, Mary, and I will read some lines which may
interest you, as being an admirer of poetry as well as of these
remembrances of bygone days.”
Chapter VI

The mild blue sky, the silvery moon, sailing in its unclouded
brightness,
And the soft breeze of night, wafted upon the gentle summer air,
All breathe of peace and loveliness; man’s base passions alone mar
the scene.

Although Mrs. Wilson lived in comparative retirement, yet her


house was the abode of hospitality. Many valuable friends of her
younger years, and of her husband, still kept up that friendly
intercourse which had always been a source of pleasure and
improvement; and among them were many, not only the most pious,
but the most enlightened and amiable characters of the day. In their
society the young people became accustomed to that true
politeness, that delicate wit and refined conversation which is the
sure index of good breeding and high intellect. While surrounded by
visitors of this class they could not so much regret the loss of their
evening entertainments, and, when left with only their own domestic
circle, they returned to them with renewed enjoyment. Some
evenings had elapsed during one of those pleasant seasons of
visiting, and the continuation of the Tale, which had so interested
them, had been necessarily delayed, but at length the time arrived
when they were again alone and at liberty to pursue their course of
reading.

“The moonbeams shone in rich splendor upon the massy walls


and towers of the imperial palace and illumed the glittering arms of
the guard who surrounded it. Preparations for a feast were going on
and strains of soft music were heard within. Its magnificent
apartments were blazing with light and sparkling with gold and silver
ornaments and the fragrance of the scented draperies diffused itself
through their vast extent. In an inner chamber, more gorgeously
decorated, and hung with cloth of gold, the bordering of which was
heavy with jewels, reclined upon a luxurious couch the infamous
Nero, the lord of all this splendor, but despised and contemned by
even the meanest of his subjects. His purple robe hung in rich folds
over the silver drapery of his couch, his long, perfumed hair was
parted over his white forehead, displaying an effeminate
countenance which, to a casual observer, would show none of those
traits of revengeful malice or diabolical cruelty which were the
characteristics of the despotic Emperor. His jeweled fingers pressed
lightly the strings of a lute and the careless indolence of his attitude
expressed total indifference to everything excepting his own ease. A
few attendants stood at the door and his favorite freedman waited
near the couch to receive the first indications of his pleasure.
“Anicetus,” said he, at length, raising his heavy eyes, in the
expression of which alone might be seen the evil passions of his
nature, “did you instruct my guards to admit the woman whom we
encountered at the bath?” “I did, mighty Emperor,” was the answer.
“Repeat to me the words of her address.” “My lord, to the best of my
recollection, these were her very words: ‘The star of thy nativity
wanes; wouldst thou know more? admit me ere thy revel begins.’”
The complexion of Nero grew paler as he said in a low tone: “Dost
thou believe in the prophetic gifts of these Sybils?” “The star of Nero
will always be in the ascendant,” said the freedman. “Is not his word
the law of Rome? and not of Rome only, but of the whole world?”
and he bowed to the ground in cringing servility. “Nevertheless, I
would hear what this woman would reveal; see that she is admitted
at the time. Some wine, Anicetus. What insufferable insolence in
Servius Galba to interfere in the execution of my will! His haughty
ambition requires pruning. Reprieve! pardon the arrogant Christian,
who has dared to brave my power! No! by Jupiter, the extremest
tortures shall punish his audacity; we will see if his demeanor will
retain its insulting composure. Are all my orders executed? Is
everything in readiness?” “Everything, my noble lord; all has been
prepared according to your directions, and your decree to that effect
has been given to the impudent Christian, who will have the night to
contemplate the certainty of his deserved fate.” “It is ’well,” said
Nero, and a malignant smile passed across his features and, while
carelessly tuning his instrument, his thoughts were apparently rioting
in the prospect of the gratification of his revenge. At this moment the
woman, who, by his order was suffered to enter, appeared at the
door of the apartment. As the freedman met her with an impatient
gesture, she waved him aside and, with a firm step and commanding
air, advanced to the couch, from which Nero had started. The same
dark and piercing eyes were fixed upon him which had terrified
Cleone and the same deep and hollow voice sounded in his ear.
“The decree of Fate is even now passing; the fiat of justice is being
issued; thou, who hast arrogated to thyself the powers of life and
death at the dictates of thine own base passions, tremble before a
Power in whose sight thou art but as a grain of dust, more degraded
than the meanest worm of the ground thou hast polluted. The Sun of
the universe will arise, but not for thee; the breeze of the mountains
will refresh all nature, but its healthful influence will impart no life to
thine inanimate form; Emperor of Rome! the sands of your life are
few and fast ebbing!” Nero had stood motionless and as she stayed
her denunciations he sank again upon his couch, but a moment
elapsed, when rage and anger glowed in his countenance, before
pale as marble. “Wretch!” said he, “thy fate is sealed, tortures and
death await thee.” Unshrinkingly she stood before the tyrant, unawed
she witnessed his deadly rage. “Yet retrace thy steps,” she said,
“man of many crimes, while yet in thy power repair those evils which
have not passed beyond thy influence. From the deep abyss of thy
guilt and infamy look up; for, far through the fearful gloom the rays of
the sweet star of mercy may reach even thee. For me, I am beyond
your power; you can neither save nor destroy me. Nero, to purchase
the slender chance for mercy which is yet yours I would barter life
and yield it amidst all the torments the art of man could inflict. But my
time has elapsed; we meet no more on earth.” So saying, before the
dismayed Emperor could collect his scattered thoughts, she passed
from the apartment and from the astonished gaze of the attendants
who, though distant spectators of the scene, had not heard what had
passed. “Draw near, Anicetus,” said Nero, as his freedman
approached. “Where did Galba direct his steps when he left our
presence? I liked not his haughty bearing.” “To the Senate chamber,
my lord.” “Ha! are the Senate together tonight? for what purpose?” “I
know not, most mighty Emperor; the doors of the chamber are
closed.” “The slaves! do they dare?” He strode the apartment with
hasty steps, his cheeks blanched with passion. “Discover,” said he,
“the cause of this secret sitting; by my head, they shall dearly rue
this audacity. Bring me the report without delay.” The freedman bent
his body in obedience and withdrew. Left alone, the restless motions
and perturbed demeanor of the Emperor expressed the agitation of
his mind. At times he would gnash his teeth in anger, then strong
lines of terror and dismay would cross his features. At length,
throwing himself upon the couch, he covered his face with his hands
and appeared lost in thought. The lowliest goatherd among the
Appenines, who, lying down at night with but the hard ground for a
pillow and a canopy of boughs for a shelter, knows not where to find
his daily food, was happier than this lord of Italy. Of what avail was
all this pomp to him, whose splendid robes covered a heart beating
with terror and alarm? The abode of suspicion and fear, torn with the
pangs of dark remorse, but still raging with the most horrid passions,
to gratify which the country which he was bound to serve and protect
was made to bleed at every pore? The meanest serf, the most
degraded slave throughout this vast empire would have refused to
exchange situations with this lordly tyrant could they have realized
the horrors of his guilty conscience. At one moment he would devise
means to crush the Senate at a single blow; then the words of the
Sybil, recurring to his mind, the idea of conciliation would be
uppermost, and, though his whole frame trembled with impotent
rage, yet he would determine to practise his powers of dissimulation
and defer the gratification of his revenge to a more fitting opportunity.
The superstitious terrors of his intellect were all aroused, his
cowardly heart quailed at the shadow of coming events which he
knew would overwhelm him, and his revengeful passions were all in
wild commotion.
A slave, bending before him, announced Lucius Flavius, and,
collecting his thought, and endeavoring to smooth his brow to
composure, he ordered that the patrician should be admitted.
Herbert was here interrupted by the call of some persons upon
business which might detain him some time, to the great annoyance
of the little party. A pleasant conversation, however, commenced
upon the influence of superstition over mankind throughout all ages
of the world. “Even in our enlightened age,” said Mrs. Wilson, “we
find many who are slaves to superstition in some of its various forms,
but its influence is milder and gradually decreasing. Within a century
and a half persons whose minds were enlightened, of undoubted
piety, and who would have smiled in derision at the superstitious
observances of the ancient Romans, professed full faith in witchcraft,
that most terrific of all delusions.” “Oh,” said Mary, “I never hear the
relation of those times without a shudder. What could have been the
cause of such frightful credulity?” “It is shrouded in mystery,” said
Mrs. Wilson, “and, probably, in this world we shall never know. Let us
be thankful that no vestiges of such infatuation are left, but the sad
spot where so many victims to its maddening influence perished.”
“Even here,” said Elizabeth, “we are not exempted from this
universal passion; we, too, have had our renowned fortune teller.”
“Oh, yes,” said Susan, “I overheard Phoebe, the other day, gravely
recounting the wonderful predictions of this redoubtable Sybil.” “Was
Moll Pitcher a Sybil?” said Charles. “She would have passed for one
in ancient times, Charles,” said his mother, “and, with her shrewd
countenance and small, black eyes, aided by her red cloak and
hood, might, I think, have played her part quite respectably. Her
dwelling, too, would be appropriate for such a character; desolate
and dreary, at the foot of the high rock, and embellished with a tall
memento of one of the monsters of the ocean, the rib of a whale. I
will read some lines upon her name and character by some witty
poet of the day:
MOLL PITCHER

“Ah! dost thou laugh at the familiar name?


Deride and ridicule her world-wide fame?
Dost jest at sorcery and witchcraft’s power,
At whose dread magic even wise men cower?
Laugh, if you will; the time has long gone by
When Moll would change your laugh into a cry.
Know, daring sceptic, that in days of yore
No thoughtless wight ventured to brave her power.
Should even the smile incredulous appear,
Woe to its author, luckless his career!
Oh, the sharp pains which seemed to vex his bones,
How grievous ’twas to hear his piteous moans!
At midnight hour, when bites and itching smart
Assailed his flesh and saddened his poor heart,
Even his household gods seemed leagued to slay
His bosom’s peace and drive his joys away;
On his own threshold his unwary feet
Would stumbling slip and sad disaster meet;
His faithful dog would snarl at his caress,
And wholesome food with racking pains distress.
Oh, witch implacable! how oft thy form
At distance seen caused the scared youth to run.
How oft the thrifty housewife banned thy name
While toiling o’er the slowly turning cream!
How oft thy old red cloak, streaming afar,
Foreboded evil and excited fear!
Fear to the maiden, lest the raging sea
Had whelmed in death her much-loved sailor boy;
Fear to the bashful swain, let the wished beam
Of Katie’s smile should prove an empty dream;
Dread to the merchant, lest the wild, weird glance
Should tell of loss, of shipwreck and mischance;
And even the parson grave forebore to frown
As her dark eye flashed o’er his passing form.
For why? His memory this precaution lends
‘Of the unrighteous Mammon to make friends.’
Yet oft the village gossip told a deed
Of kindly pity to the poor man’s need;
How Moll would stand beside the bed of death
And bathe the pallid brow and catch the breath,
The dying breath, and soothe the last sad moan,
Breathed for the dear ones he should leave alone.
That many a smile relieved the falling tear,
As ’midst a childish group Moll would appear,
While her capacious pocket would bring forth
Rich stores of apples red to raise their mirth.
Long years have rolled away, yet Molly’s fame
Still lingers round the spot that bears her name.
‘Moll Pitcher’s house,’ a lonely spot, full sure,
Though some there were who sought her close-shut door,
Some restless ones, who longed to know their fate.
Unwilling the decrees of Heaven to wait;
As the still evening closed, with awe-struck glance.
Their lingering feet would stealthily advance.
With timid knock they waked the echoes lone,
Then started back, half tempted to return.
But ’tis not ours to tell the mystic rites
Attendant on those dark and fearful nights,
Though oft I’ve heard my aged grandame say
That better far ’twould be to stay away.
Now, o’er the mound, where rests her mortal form,
The wild grass waves with low and gentle moan;
There sleeps the dust, so restless once, and there
’Twill rest, no longer to excite a fear.
There let the memory of her follies lie;
The memory of true worth will never die.”

“Did you ever see a witch, mother?” said Charles. “If you will listen,
my son, I will tell you a story, the only one relating to a witch, which
ever came to my certain knowledge.
“When I was a tiny school girl there stood a lonely little house at
the foot of a rising ground on the direct road to our school house;
there were no trees about it, but a few choke berries and alder
bushes, for there was a marshy piece of ground there. A very small
lot was cultivated as a garden by the hands of its only inhabitant,
poor old ‘Aunt Lois,’ as everybody called her. Nobody knew any
harm of Aunt Lois, but every body said ‘Certainly she was a witch.’
The time had passed when witches were hanged or burned, so Aunt
Lois lived peaceably in her own home, but many wonderful stories
were told about her, such as that she was seen churning butter in the
night, and, though nothing could be nicer or sweeter than her butter,
yet some wise people asserted ‘that she must have help about it
which nobody knew of.’ Old Joe Hart said that he had seen a
company of witches, riding on broomsticks through the air, with Aunt
Lois at their head with a cap and long cloak on, and a wand in her
hand. This, he said was “just as true as anything he ever said in all
his life,” but as Joe was noted for telling great stories, people would
have been glad of better authority. But no part of the community was
more troubled about these stories than the children belonging to the
school, and, though the boys blustered a good deal and said ‘Who’s
afraid?’ yet it was observed that they always kept the side of the lane
farthest from Aunt Lois’s house; and, as to the girls, they would
scramble over the fence and run through a swamp rather than go
near it. An event, however, occurred which not only quieted their
fears, but even made Lois popular in their opinion. It was a warm
afternoon in the summer, when a little troop of boys and girls were
returning from school, when they espied among the wet ground at
the foot of the hill, near the old woman’s house, a cluster of beautiful
lilies. Never were any wild flowers so much sought for as those lilies,
for they were very scarce and of rare and beautiful colors. ‘I know I
can get some,’ said Catherine, and, followed closely by two others,
she bounded over the low wall and, without taking thought of the
swamp, she sprang forward to be the first to gain the wished-for
prize. But soon the ground began to give way beneath her feet, but
she had almost gained the flowers, and, supposing that by one more
leap she should gain sure footing, she jumped forward, but down she
sank, deep, deep in the mire, and there she was planted, unable to
stir her feet, and imagining her little body was going, too, she did not
know where. She was near enough to clasp the tall stems of the lilies
and clung to them as if for support, but the slender roots gave way
and, though she had gained the desired objects, yet she would
joyfully have given them up to her frightened companions, who had
stopped just before they arrived at the fatal spot, could she have
been safe with them. ‘Do help me, Martha; do take my hand, Susie,’
screamed the little girl, but when they dare not come further and
were turning back, she began to sob and cry most piteously. But, just
then, terrible to behold, Aunt Lois’s door opened and, to our great
dismay, she appeared. What a scampering now ensued! The boys
jumped over the wall and the girls ran, without looking back, until
they had gained what they considered a safe distance from the
dreaded spot, but the little girl was left, unable to stir. She covered
her face with her hands to shut out the sight of the old witch, but she
heard her step and the terror of she knew not what almost took away
her senses. ‘For mercy’s sake, my little dear,’ said Aunt Lois, ‘why
did you come into this wet, boggy place? I don’t know as I can get to
you, but put out your hand. If I should get stuck here, too, we should
be in a pickle.’ Catherine obeyed, for the voice of Aunt Lois sounded
kind and pleasant, and, with a strong pull, she extricated the little girl,
but a sad sight was displayed. Her feet were black with the mud of
the swamp, but, her shoes being tied on, she did not lose them. And
now, to the great terror of the children, who were watching from their
hiding places, Lois carried the little girl into her house, and solemn
was the consultation as we gathered together and debated upon her
fate. Such long and dismal faces are seldom seen, such terrible
stories were told as made the eyes of the younger children dilate
with dismay. But at this moment the little Catherine was seen running
toward us. ‘Aunt Lois isn’t a witch,’ said she, ‘see, she has washed
my shoes and the bottom of my dress, and she has given me some
doughnuts and some apples, and picked me a whole bunch of lilies.’
The charm was at an end. Aunt Lois’s cake and apples were eaten
with great relish and, ever after, in the opinion of the children, Aunt
Lois was ‘a grand, good old woman.’”
“I wish all witch stories would end as well as this,” said Susan.
“And that all witches were as good as Aunt Lois,” said Charles.
Chapter VII

Judea’s daughters mourn her blighted soil,


Her dark-eyed sons in foreign regions toil,
But Holy is the land where Jesus trod
Sacred its soil, though desolate and sad.

A bright, clear, cold Sabbath morning dawned. The smooth snow


sparkled as if sprinkled with diamonds, and the bracing atmosphere
seemed to infuse new life into creation. The strict habits of our
Puritan fathers, in regard to public worship, were not forgotten in the
family of Mrs. Wilson, and, when, all meeting at their social evening
conversation, many remarks were made upon the exercises of the
day, no carping criticisms, no sarcastic observations were indulged
in, or would have been permitted. Ministers, in those days, were both
loved and reverenced; loved for themselves, and reverenced for their
holy vocation, and, generally grew old among a people to whom they
were attached by the strongest ties, whose interests were theirs, and
whose children were considered their own. There is no more
beautiful description of a country clergyman, and none that more
generally applies to the times of which I am writing, than
Goldsmith’s. The pastors, in those days, literally “allured to brighter
worlds, and led the way.”
After a day spent in listening to the words of one of those
emphatically good men, the evening fire was surrounded by our little
company, who were comparing notes upon the services of the day.
The subject was Christ choosing his disciples, and, one of the
remarks of one of the speakers was, that because the first followers
of Christ were probably illiterate men, it should not be inferred that
learning was not necessary for ministers of the present day. Almighty
power could inspire them with wisdom, without human means, and,
that was then the case, but the miraculous interposition of
Providence was not now granted, therefore, education was a most
useful auxiliary to piety. An interesting conversation upon the subject
then ensued. At length Mary reminded Herbert of his promise to read
them some poetry, and he read as follows:

“The setting sun shone bright and clear on Galilee’s dark sea,
Lovely was its reflection of the clear and cloudless sky.
The fisher’s boats were scattered o’er the broad and deep expanse
And the mingled sounds of busy life re-echoed from its banks,
Here Naz’reth’s populous city stretched its crowded noisy street,
And there Capernaum’s lofty towers the passing traveler greet;
Here the wild fig tree bends beneath its luscious watery load,
And there the light green olive spreads around the mountain side.
Oh! chosen land; how lovely then thy hills and valleys seemed,
That ’midst such beauty dwelt such sin, ah! who would then have
deemed,
Upon those waves, one humble bark was making for the land,
Weary and faint, its inmates joyed as they approached the strand.
A life of toil and scanty fare, these humble fishers led,
And, wearily and patiently they earned their daily bread;
The careless glance would scarce remark aught in their aspect rude
Save the dull look of untaught men, in discontented mood,
But observations practiced eye, would trace the lines of thought,
Of the sedate intelligence of minds with wisdom fraught;
Would mark the quick and varying glance of passion, strong and
deep,
Though, now, within the calm, cold breast, the stormy feelings sleep;
Would note the traces of that zeal, which oft in after days
Glowed in those hearts, and warmed the world by its reflected blaze,
Which led those men, so humble now, with firm and dauntless mien,
Tortures to brave, and even death, with hearts firm and serene;
But why their looks of earnest awe, now bent towards the shore?
Why are those features roused to life, so still and calm before?
Mark you, on yonder point that form? is it of earth or heaven?
Though lowly are his robes, such grace is not to mortals given,
Thy coast, O favored Galilee! Such foot ne’er pressed before;
Such voice, O lovely lake! ne’er waked the echoes of thy shore.
Mark but that pure and holy brow, where heaven’s own perfect
peace
Sits calm enthroned, and bids the world’s tumultuous passions
cease.
That eye, whose quick and piercing glance, whose full and brilliant
light
Searches each heart, and reads each thought of those who meet its
sight,
Then listen to that sacred voice, that simple ‘Follow me.’
Aye, blessed Jesus, aye; through life, to death, we follow thee;
Such is the quick, the glad response, their earnest gesture shows,
See, in their looks the free assent, e’er from their lips it flows,
Peter! thy dark and flashing eye, thy lips compressed and stern,
Says ‘though all men forsake thee, Lord, yet is my purpose firm’;
And it was firm, though the dark tempter sought, by many a wile,
To lure him from his plighted faith, and lead his heart to guile;
Yes; it was firm, for with his blood he made the compact sure,
And, on the Rock of Peter’s faith, the church will rest secure.
The waters of that hallowed lake still wash that honored shore
Still o’er its waves the setting sun does his bright radiance pour,
But on its dark blue surface glides no solitary bark,
And o’er that once fair land, a cloud hangs heavily and dark.
Heaven has received again to bless that pure and blessed One,
His chosen martyred followers, too, victory o’er Death have won,
But memory hangs, with cherished love, round scenes his presence
blest,
And dwells with fond affection on the soil his footsteps pressed.”

“I like very much to hear Herbert read poetry,” said Charles.


“Mother, may he read those lines called ‘Early Recollections?’ They
refer to scenes in our own town, Susan, and I know you will like
them.” “Why should Susan like them more than the rest of us,
Charles?” said Mary. “Oh. I think they are more suited to her taste.” “I
must certainly hear them,” said Susan, “if it were only to know
whether Charles has judged rightly of my taste.” “I will endeavor to
find them tomorrow,” said Mrs. Wilson, “and I hope they will serve to
amuse you.” At the first convenient opportunity Herbert continued the
tale of the early Christians.
The delicious coolness of the evening breeze, after a day of
uncommon heat was, of itself, a temptation sufficient to draw many
into the open air, and the streets of Rome were thronged with her
citizens. Here might be seen the rich carriage, borne by slaves in
livery, on whose soft and luxurious cushions reclined the haughty
noble; there, the patrician, with his train of attendants, and the
wealthy plebean, conscious of his inferior rank, but emulating the
proud bearing of his rival. Chairs and litters passed in quick
succession, and freed men and slaves jostled each other. From the
stately palaces resounded the notes of revelry and mirth, and from
the theatres, the sounds of music and dancing. In the opening,
before one of the courts, were gathered a crowd of listeners, around
one of those gifted poets, who, without forethought, composed and
recited upon any given subject, with ease and gracefulness, and are
rewarded not only by gratuities of money, but by the rapturous
applause of their hearers. Through one of the streets passed a
funeral procession, for, in Rome, all their funeral ceremonies were
performed by torchlight and much pomp and parade was displayed
upon the occasion in honor of the deceased. Thus life, with its
shifting scenes, its hopes and fears and conflicting passions, were,
at this time, in full contrast with the startling reality of death; though
few heeded the solemn warning. A hasty glance, some words of
condolence or commendation of the deceased, and the proud
pageant was forgotten. Amidst all this bustling confusion might be
seen some, apparently persons of distinction, whose air of mystery
and whispering conferences portended some event of importance.
Two citizens met near the Temple of Fortune; “Health and happiness,
noble Varro,” said a rich patrician to a stately noble, “may the deities
be propitious; have you heard the rumor?” “I have been witnessing
the betrothal of my son to the daughter of Publius Dentatus, and
have heard no rumor. Of what nature?” “A most happy betrothal;
may their years be auspicious! The reports are of a most astounding
character. It is rumored that the Senate, in full council, have
condemned Nero, and, that Servius Galba, so lately returned from
Spain, will be chosen, by the soldiery, as his successor.” “And, would
Galba be the choice of the Senate, Licinius?” “Perhaps not, but he is
the favorite of the legions from Spain, and beloved by the soldiers,
generally, and they could find no fault with the choice, unless it be
the severity of his manners.” “He is a good and honorable man,” said
the elder, “but he will find the rank and title of Emperor but a thin
gilding to the bitter pill of royalty he must swallow. But, the world will
last our day, Licinius, let the wheel go round.” And they parted. At the
turning of one of the streets, a knot of citizens were conferring. “How
is this, Sempronius?” said one, “what will be the consequence of this
decree of condemnation, of which we hear so many rumors? Will the
Emperor abdicate, or have his enemies determined upon his death?”
“Vengeance will not always sleep, fellow citizens,” said the one who
was addressed; “Who is not an enemy to the detestable vices of
Nero? and what wickedness is there in the whole catalogue of crime
which he has not committed?” “Nay, Sempronius,” said a man with a
stern and forbidding countenance, “he has done good service to the
State, by exterminating those Christians.” “By our household deities,”
said another, “I know not that, for the sect is like the Hydra of old, as
fast as one is exterminated, as you say, a score appear in his place.
I am for stopping these executions at once, and then we shall see if
this heresy will not die of itself.” “But, said the first speaker, “will not
Nero set the Senate at defiance? He has his favorites, and may yet
make a stand.” “Not so,” said Sempronius, “his nature is cowardly,
and at the first intimation of danger, he would shrink from it with
terror. He needs no accuser but his own guilty conscience; he has
waded in the blood of innocence, and will yet be deluged in its
avenging waves.” The company dispersed, each in his several path.
With a hurried step, the freedman of Nero was seen ascending the
steps of the palace; he was greeted by one of his fellow servants,
“Whither so fast, Anicetus? One would think the avenger was at thy
heels.” “He is,” said the freedman. “There is something wrong in the
wind,” said the questioner, “there is some cause for so much stir and
commotion in the city,” continued he, addressing one of the guards,
“and the military, without the walls are in motion, for the trumpets
have sounded.” “Well,” said the other, “let what will come, my duty
lies here.”
We will now return to the entrance of Lucius Flavius into the
apartment of Nero, in the imperial palace. With a firm and lofty step,
but a respectful demeanor, the young and noble defender of
innocence, advanced, supporting the sister of Curtius, who, though
her complexion was pale, and her form tremulous with emotion,
shrank not from the haughty and insolent regard of the tyrant. “How
is this, my Lord Lucius; what fair votary of Venus have you
introduced to our presence with so little ceremony? Methinks some
more formal introduction were befitting so much beauty.” “Innocence,
my Lord, the Emperor, may be always confident in its own resources,
and sorrow has claims superior to all formal observances. The
maiden before you is the sister of Quintius Curtius, and her errand is
to solicit, even yet, the life and freedom of her brother.” Cleone slid
from the arm of her protector, and bent her knee before Nero. “We
are orphans,” said she, “my brother and myself, children of one of
Rome’s noblest citizens. Our father fought his country’s battles,
defended her liberty and gloried in her prosperity. Our ancestors
gave their lives and treasures for her benefit, and my brother would
yield his heart’s blood for the welfare of his native land; we are alone
in the world; noble Emperor, grant me the life of my brother.” The
sweet pleading tones of her voice, the earnest expressions of her
eyes, would, it would seem, have produced some feeling, even in the
hard heart of Nero; such was not the case. With a malignant sneer,
he said: “And so permit him to convert you, fair damsel, to the faith of
the Nazarene? By the beard of Silenus, that would be sacrilege to
bind so alluring an object in the galling chains of that cynical sect.
Not so, my beautiful grace; love for our country influences us to
cleanse it of these fanatical reformers, who are attempting to subvert
its established principles, and overturn our faith in a religion which
has stood the test of ages. He must suffer for his obstinacy; but, for
you, fair maiden, you shall be under especial care and protection.”
With an indignant gesture, Flavius attempted to raise Cleone, but,
resisting the effort, her eyes flashing, and her voice becoming more
firm, “Yet a moment, haughty Emperor, your life is in my
power,”—“What! ho, help here, slaves!” “Stay, Emperor,” said
Flavius, “there is a secret conspiracy against your life, accidentally
discovered. She only can tell you the names of the conspirators, and
its details. Give to her prayers the life of her brother, and your life
may be preserved.” “Refuse me,” said Cleone, “and, so sure as you
are now living, so certain is your destruction.” A scowl of rage
distorted the countenance of Nero. “There are ways, my haughty
young dame, to compel such refractory tempers to confession.”
“Before your cruel purpose could be executed,” said Cleone, “the
time would have elapsed when your life might be saved. Death is
fearful to all, were it only for the uncertainty of the prospect beyond.
Is your conscience so pure that you dare look upon its near
approach without alarm? Will you not shrink from encountering its
gloom, to you the dark mystery of the future?” She was interrupted
by the hasty entrance of the freedman, who, bending low before the
Emperor, addressed to him some communication, which, first
suffusing his face with crimson, soon left it of a deadly paleness.
Fear and irresolution marked his features. He gave some hasty
orders, and appeared lost in thought for a short time. At length,
seeming to have formed a determination, he turned to Flavius.
“Young lord,” said he, “time does not admit of delay; let this maiden
give me, in a few words, the outline of this conspiracy, and then,
upon one condition, I will release the Christian.” “Give us an order to
that effect, my lord Emperor, and you shall know all,” and, while
Cleone trembled between hope and fear, Nero wrote upon a leaf of
his tablets, “Release the Christian prisoner, Quintius Curtius,” and
tearing it from the book, affixed his seal, and gave the order to
Flavius. Hurry and dismay marked his motions, and, turning to
Cleone, he commanded her to make the disclosure. In a clear,
distinct manner, she related the circumstances, and mentioned
Caius Piso as the principal conspirator. He muttered between his
teeth, “Let me but escape this first danger, and I will defy Piso and
his retainers.” “Go,” said he, aloud, “leave the presence, yet, stay,
Lucius Flavius, the condition is not yet complied with.” In a low
constrained voice, he said, “I have just received intelligence of an
insurrection in the army without the walls, and that the traitors have
expressed their determination of deposing me, and electing Servius
Galba. I know not how far the discontent extends, perhaps the
Senate have dared to connive at it,” and his frame trembled, and he
grew more deadly pale. “The condition I make with you is, that, if

You might also like