0% found this document useful (0 votes)
5 views

Programming In C Volume 2 Composite Data Structures And Modularization Zhou download

The document is about 'Programming in C Volume 2: Composite Data Structures and Modularization' authored by Xingni Zhou, Qiguang Miao, and Lei Feng. It covers various topics including arrays, pointers, composite data structures, functions, and modularization techniques in C programming. The document also provides ISBN details and links to related products and additional resources.

Uploaded by

nonyadorado
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)
5 views

Programming In C Volume 2 Composite Data Structures And Modularization Zhou download

The document is about 'Programming in C Volume 2: Composite Data Structures and Modularization' authored by Xingni Zhou, Qiguang Miao, and Lei Feng. It covers various topics including arrays, pointers, composite data structures, functions, and modularization techniques in C programming. The document also provides ISBN details and links to related products and additional resources.

Uploaded by

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

Programming In C Volume 2 Composite Data

Structures And Modularization Zhou download

https://ebookbell.com/product/programming-in-c-
volume-2-composite-data-structures-and-modularization-
zhou-22736722

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Programming In C Volume 2 Composite Data Structures And Modularization

https://ebookbell.com/product/programming-in-c-volume-2-composite-
data-structures-and-modularization-50338946

Ms Course 10266a Programming In C With Microsoft Visual Studio 2010


Trainer Edition Volume 2 Microsoft

https://ebookbell.com/product/ms-course-10266a-programming-in-c-with-
microsoft-visual-studio-2010-trainer-edition-
volume-2-microsoft-2113634

Thinking In C Volume 2 Practical Programming Us Ed Bruce Eckel

https://ebookbell.com/product/thinking-in-c-volume-2-practical-
programming-us-ed-bruce-eckel-1136612

Programming In C Volume 1 Basic Data Structures And Program Statements


Xingni Zhou

https://ebookbell.com/product/programming-in-c-volume-1-basic-data-
structures-and-program-statements-xingni-zhou-50339330
Ms Course 10266a Programming In C With Microsoft Visual Studio 2010
Trainer Edition Volume 1 Microsoft

https://ebookbell.com/product/ms-course-10266a-programming-in-c-with-
microsoft-visual-studio-2010-trainer-edition-
volume-1-microsoft-2113632

Art Of Computer Programming Volume 4a Combinatorial Algorithms Part 1


1st Edition Donald E Knuth

https://ebookbell.com/product/art-of-computer-programming-
volume-4a-combinatorial-algorithms-part-1-1st-edition-donald-e-
knuth-2226790

Programming In C Object Oriented Features Laxmisha Rai Editor China


Science Publishing Media Ltd Editor

https://ebookbell.com/product/programming-in-c-object-oriented-
features-laxmisha-rai-editor-china-science-publishing-media-ltd-
editor-51127748

Programming In C For Engineering And Science 1st Edition Nyhoff

https://ebookbell.com/product/programming-in-c-for-engineering-and-
science-1st-edition-nyhoff-55234332

Programming In C Part One Introduction To C Leonard Robbie

https://ebookbell.com/product/programming-in-c-part-one-introduction-
to-c-leonard-robbie-56204050
Xingni Zhou, Qiguang Miao and Lei Feng
Programming in C
Also of interest
Programming in C, vol. : Basic Data Structures and Program
Statements
Xingni Zhou, Qiguang Miao, Lei Feng, 
ISBN ----, e-ISBN (PDF) ----,
e-ISBN (EPUB) ----

C++ Programming
Li Zheng, Yuan Dong, Fang Yang, 
ISBN ----, e-ISBN (PDF) ----,
e-ISBN (EPUB) ----

Elementary Synchronous Programming


Ali S. Janfada, 
ISBN ----, e-ISBN (PDF) ----,
e-ISBN (EPUB) ----

MATLAB® Programming
Dingyü Xue, 
ISBN ----, e-ISBN (PDF) ----,
e-ISBN (EPUB) ----

Programming in C++
Laxmisha Rai, 
ISBN ----, e-ISBN (PDF) ----,
e-ISBN (EPUB) ----
Xingni Zhou, Qiguang Miao and Lei Feng

Programming in C

Volume 2: Composite Data Structures


and Modularization
Authors
Prof. Xingni Zhou Qiguang Miao
School of Telecommunication Engineering School of Computer Science
Xidian University Xidian University
Xi’an, Shaanxi Province Xi’an, Shaanxi Province
People’s Republic of China People’s Republic of China
xnzhou@xidian.edu.cn qgmiao@xidian.edu.cn

Lei Feng
School of Telecommunication Engineering
Xidian University
Xi’an, Shaanxi Province
People’s Republic of China
fenglei@mail.xidian.edu.cn

ISBN 978-3-11-069229-7
e-ISBN (PDF) 978-3-11-069230-3
e-ISBN (EPUB) 978-3-11-069250-1

Library of Congress Control Number: 2020941966

Bibliographic information published by the Deutsche Nationalbibliothek


The Deutsche Nationalbibliothek lists this publication in the Deutsche Nationalbibliografie;
detailed bibliographic data are available on the Internet at http://dnb.dnb.de.

© 2020 Walter de Gruyter GmbH, Berlin/Boston


Cover image: RomoloTavani/iStock/Getty Images Plus
Typesetting: Integra Software Services Pvt. Ltd.
Printing and binding: CPI books GmbH, Leck

www.degruyter.com
Contents
1 Arrays 1
1.1 Concept of arrays 1
1.1.1 Processing data of the same type 1
1.1.2 Representation of data of the same type 5
1.2 Storage of arrays 6
1.2.1 Definition of arrays 6
1.2.1.1 Definition of arrays 6
1.2.1.2 Reference of array elements 7
1.2.1.3 Storage characteristics of arrays 8
1.2.1.4 Comparison of variables of the same type with plain
variables 9
1.2.2 Initialization of arrays 10
1.2.2.1 Initialize all elements 10
1.2.2.2 Initialize some elements 11
1.2.2.3 Array size determined by number of initial values 11
1.2.3 Memory layout of arrays 11
1.2.3.1 Memory layout of one-dimensional arrays 11
1.2.3.2 Memory layout of two-dimensional arrays 11
1.2.4 Memory inspection of arrays 12
1.3 Operations on one-dimensional arrays 16
1.4 Operations on two-dimensional arrays 26
1.5 Operations on character arrays 37
1.6 Summary 45
1.7 Exercises 48
1.7.1 Multiple-choice questions 48
1.7.2 Fill in the tables 50
1.7.3 Programming exercises 51

2 Pointers 53
2.1 Concept of pointers 53
2.1.1 Reference by name and reference by address 53
2.1.2 Management of storage space 55
2.1.2.1 Management of computer memory space 57
2.1.2.2 Storage rules of data in memory 58
2.1.2.3 Address management in memory 58
2.1.3 Definition of pointers 60
2.1.3.1 Comparison of pointer variables and plain variables 60
2.1.3.2 Syntax of pointer definitions 61
2.2 Pointer operations 61
2.2.1 Pointer operators 62
VI Contents

2.2.2 Pointer operations 62


2.2.3 Basic rules of pointer operations 62
2.2.4 Purpose of pointer offsets 67
2.2.4.1 Introduction 67
2.2.4.2 Discussion and conclusion 68
2.2.4.3 Program verification 69
2.2.5 Concept of null pointer 69
2.2.5.1 Meaning of NULL 69
2.2.5.2 Null pointer 71
2.3 Pointers and arrays 72
2.3.1 Pointers and one-dimensional arrays 72
2.3.2 Pointers and two-dimensional arrays 77
2.4 Pointers and multiple strings 82
2.4.1 One-dimensional pointer array and pointer to pointer 84
2.5 Summary 87
2.6 Exercises 87
2.6.1 Multiple-choice questions 87
2.6.2 Fill in the tables 89
2.6.3 Programming exercises 91

3 Composite data 93
3.1 Concept of structures 93
3.1.1 Introduction 93
3.1.2 Storage solution of mixed data table 94
3.1.2.1 Discussion of possible storage solution of mixed data table 94
3.1.2.2 Issues of constructing “combinatorial data” 95
3.1.2.3 Key elements of constructional data 95
3.2 Storage of structures 96
3.2.1 Type definitions of structures 96
3.2.2 Definition of structure variables 98
3.2.3 Structure initialization 99
3.2.4 Memory allocation of structure variables 100
3.2.4.1 Definitions related to structure 100
3.2.4.2 Memory layout of structure variables 100
3.2.4.3 Inspection of memory layout of structure variables 100
3.2.4.4 Data alignment of structures 102
3.2.5 Referencing structure members 105
3.3 Applications of structures 106
3.4 Union 117
3.4.1 Introduction 117
3.4.2 Memory layout of unions 118
3.4.2.1 Union-type definition 118
Contents VII

3.4.2.2 Union variable definition 119


3.4.2.3 Union member reference 119
3.4.2.4 Comparison of unions and structures 120
3.5 Enumeration 124
3.5.1 Introduction 124
3.5.2 Concept and syntax of enumeration 126
3.5.3 Example of enumerations 127
3.5.4 Rules of enumerations 128
3.5.4.1 We cannot assign values of other types to an enumeration
variable 129
3.5.4.2 Arithmetic operations are not allowed on enumeration
variables 129
3.6 Type definitions 129
3.6.1 Introduction 129
3.6.1.1 Porting of music files 129
3.6.1.2 Cases where macros are not enough 131
3.6.1.3 Define aliases for types 131
3.6.2 Syntax and applications of typedef 131
3.7 Summary 132
3.8 Exercises 134
3.8.1 Multiple-choice questions 134
3.8.2 Fill in the tables 136
3.8.3 Programming exercises 137

4 Functions 139
4.1 Concept of functions 139
4.1.1 Introduction 139
4.1.1.1 Modularization and module reuse in practice 139
4.1.1.2 Abstraction of practical problems: independent code
modules 140
4.1.2 Concept of modules 141
4.1.2.1 Coordination problems in teamwork 141
4.1.2.2 Coordination problems in modularization of programs 141
4.1.2.3 Concept of modules 142
4.2 Function form design 143
4.2.1 Methods of communication between modules 143
4.2.2 Function form design 144
4.2.2.1 Analysis of outsourcing structure 144
4.2.2.2 Abstraction of outsourcing structure 145
4.2.2.3 Function form design 145
4.2.2.4 Information transmission mechanism design 146
4.2.2.5 Three syntaxes related to functions 147
VIII Contents

4.3 Design of information transmission mechanism between


functions 149
4.3.1 Characteristics of information transmission between
functions 149
4.3.1.1 Classification of data transmitted between functions 149
4.3.1.2 Expressions of data transmitted between functions 150
4.3.2 Information transmission between functions: submission and
receiving of data 150
4.3.2.1 Submission of small amount of data 150
4.3.2.2 Submission of a large amount of data 151
4.3.3 Receiving of function results 153
4.3.3.1 Receiving function results in pass by value 153
4.3.3.2 Receiving function results in pass by reference 153
4.4 Overall function design 153
4.4.1 Key elements of function design 153
4.4.1.1 Key elements of functions 153
4.4.1.2 Relations between function syntax and key elements of function
design 154
4.4.2 Summarization of information transmission between
functions 154
4.4.2.1 Direction 1: from caller to function 154
4.4.2.2 Direction 2: from function to caller 157
4.4.3 Function call 157
4.4.3.1 Execution and calling order of functions 157
4.4.3.2 Nested call of functions 157
4.4.3.3 Correspondence between parameters and arguments 159
4.4.3.4 Syntax of function call 160
4.5 Examples of function design 160
4.5.1 Call by value 160
4.5.2 Call by reference 168
4.5.3 Comprehensive examples of functions 179
4.5.4 Parameters of the main function 191
4.5.4.1 Introduction 191
4.5.4.2 Parameters of the main function 193
4.5.4.3 Example of the main function with parameters 194
4.6 Scope 196
4.6.1 Introduction 196
4.6.1.1 Cooperation issues in teamwork 196
4.6.1.2 Outsourced projects in a flow 198
4.6.1.3 Resource-sharing problem 198
4.6.2 Masking mechanism of modules 198
4.6.2.1 Isolation of internal data 199
Contents IX

4.6.2.2 Masking rule of functions 199


4.6.3 Memory segments and storage classes 199
4.6.3.1 Memory segments of programs 199
4.6.3.2 Storage classes of variables 200
4.6.4 Masking mechanism 1: lifespan and scope of variables 201
4.6.4.1 Concept of scope 201
4.6.4.2 Attributes of variables 201
4.6.4.3 Local variables and global variables 202
4.6.5 Masking mechanism 2: scope of functions 211
4.6.6 Masking mechanism 3: restriction on shared data 212
4.7 Recursion 215
4.7.1 Case study 215
4.7.2 Concept of recursion 219
4.7.2.1 Definition of recursion 219
4.7.2.2 Type of recursion 220
4.7.2.3 Comparison of recursion and iteration 220
4.7.3 Example of recursion 221
4.8 Summary 224
4.9 Exercises 226
4.9.1 Multiple-choice questions 226
4.9.2 Fill in the tables 229
4.9.3 Programming exercises 233

5 Files: operations on external data 235


5.1 Introduction 235
5.2 Concept of files 236
5.2.1 Binary files 236
5.2.2 Text files 237
5.2.3 File termination mark and end-of-file checking function 237
5.3 Operation flow of files 238
5.4 Data communication between internal and external memory 239
5.5 Operations on files using programs 241
5.5.1 Opening files 241
5.5.2 Reading and writing 243
5.5.3 Closing files 248
5.5.4 Random access 249
5.6 Discussion on file reading and writing functions 251
5.6.1 Case 1: fprintf and fscanf 251
5.6.2 Case 2: fwrite and fread 252
5.6.3 Case 3: fprintf and fscanf 253
5.6.4 Case 4: fwrite and fscanf 254
5.7 Debugging and I/O redirection 254
X Contents

5.7.1 Code template 1 Using fscanf and fprintf 255


5.7.2 Using freopen function 255
5.7.3 Code template 2 Using freopen function 256
5.8 Summary 257
5.9 Exercises 259
5.9.1 Multiple-choice questions 259
5.9.2 Fill in the tables 261
5.9.3 Programming exercises 262

Appendix A Adding multiple files to a project 265

Appendix B Programming paradigms 273

Appendix C void type 285

Index 287
1 Arrays

Main contents
– Concept, usage, and available methods of arrays
– Introduction of representation and nature of arrays through comparison between array/
array elements and plain variables
– Storage characteristics and debugging techniques of arrays
– Programming techniques of multidimensional arrays
– Top-down algorithm design practices

Learning objectives
– Know how to define and initialize arrays as well as how to access array elements
– Be able to define and use multidimensional arrays
– Know how to deal with character arrays

1.1 Concept of arrays

Program statements and data construct programs. They are sequences of instruc-
tions created through algorithm design that conform to program control structures.
However, are we able to solve all problems after learning statements, basic data
types, program control structures, and algorithm implementation methods of C?
Let us look at a few problems in practice.

1.1.1 Processing data of the same type

Case study 1 Cracking Caesar code


Mr. Brown received an email from his son Daniel. However, the contents seemed a
little weird for an email sent by someone in elementary school: it was a meaningless
sequence “lettc fmvxlhec hehhc pszi csy”.
It later turned out that Daniel read a story of Julius Caesar and created an en-
crypted email using Caesar code to see whether his father could decrypt it.
During Roman times, Caesar invented the Caesar code to protect the information
he exchanged with his generals on the front line from being intercepted by enemy
spies. Encryption and decryption of Caesar code were done by shifting letters by a fixed
number of positions. The plaintext alphabet was shifted forward or backward by a fixed
number of positions to create the ciphertext alphabet. The number of positions shifted
was the key for encryption and decryption of Caesar code, as shown in Figure 1.1.

https://doi.org/10.1515/9783110692303-001
2 1 Arrays

Case study 1
Encryption and decryption of Caesar code

plaintext ciphertext plaintext


encryption decryption

Hello Right shift Khoor Left shift Hello


by 3 by 3
positions positions

Figure 1.1: Encryption and decryption of Caesar code.

Mr. Brown stared at the ciphertext and thought that it would not be hard to design
an algorithm to solve the problem. He could simply shift each character in the ciphertext
by one position in the alphabet and repeat this process 26 times to list all possible plain-
texts, in which the one that is not nonsense would be the real plaintext. A universal al-
gorithm could be designed using this technique to crack ciphertexts of arbitrary length.
– If the length of the ciphertext is 2, we shift letters by one position in the alpha-
bet each time and list all 26 possible plaintexts.
– If the length of the ciphertext is 10, we shift letters by one position in the alpha-
bet each time and list all 26 possible plaintexts.
– If the length of the ciphertext is 100, we shift letters by one position in the al-
phabet each time and list all 26 possible plaintexts.

Think and discuss Necessary variables in password cracking


1. How many variables are necessary for a program to handle 100 characters?
2. How should we use these variables so that the program handles data in a convenient and
unified manner?

Discussion: Solving a problem with computers involves two major steps: first, we should use
reasonable data structures to describe the problem to store data into computers; second, we
create algorithms to solve it. To answer the earlier questions, we need to find a mechanism that
describes variables of the same type and handles them consistently.

Code implementation of the algorithm that solves Caesar codes is rather complicated,
so we shall introduce it later. Before that, let us consider a reversed order problem
that is more trivial.

Case study 2 Reversing 100 numbers


Write a program that reads 100 numbers and outputs them in a reversed order.
We are going to focus on how to handle variables of the same type. For a sim-
pler description, we use variables with subscripts to represent the numbers, as shown
in Figure 1.2.
1.1 Concept of arrays 3

Case study 2
Reversing 100 numbers
We need a way to
represent variables of
X1 X2 X3 ......... Xi .......... X99 X100 the same type so that
they can be processed
consistently

Figure 1.2: Representation of 100 variables of the same type.

The flow of outputting 100 numbers backward is given in Figure 1.3. The pro-
gram reads the numbers in a loop starting from X1, and outputs them using a loop
starting from X100.

Start

for( i=1 ; i<=100; i++) Input xi ;


Xi varies with i, Xi
for( i=100; i>=1; i--) Output xi; is represented as
x[i] in programs

End

Figure 1.3: Flow of outputting numbers backward.

Variable Xi is uniquely identified by the value of i. We use x[i] to represent Xi in


programs so we can type the names using keyboards.
The code implementation is as follows:

01 int main(void )
02 {
03 int i;
04 int x[100];
05 for ( i=1;i<=100; i++) scanf ("%d", &x[i] );
06 for ( i=100; i>=1; i-- ) printf ("%d", x[i] );
07 return 0;
08 }

On line 4, the statement defines 100 variables with subscripts of type int. It is more
convenient to “batch” define variables of the same type.
It is worth noting that the starting subscripts on line 5 and line 6 do not follow
the convention of using C arrays exactly.
4 1 Arrays

Subscripts of arrays start from 0 in C. Here, we are trying to make the flow more
intuitive by not following this rule.

Case study 3 Simple table processing


Write a program that calculates the average grade of a student in six courses.
Figure 1.4 shows how to store grades and pseudo code of the algorithm. To
store grades, we use six variables, namely grade 0 to grade 5. On line 1 of the
pseudo code, int grade[6] defines 6 int variables. Note that the number of variables
is 6, but the range of subscripts is 0 to 5.

Case study 3
Simple table processing

Course 1 Course 2 Course 3 Course 4 Course 5 Course 6 Average


80 82 91 68 77 78

i 0 1 2 3 4 5
grade[i] 80 82 91 68 77 78
Pseudo code
Store grades in int grade[6]
Total score total = 0; Counter i = 0;
while i < 6
total= total+grade[i];
i++;
Average= total / 6

Figure 1.4: Simple table processing.

We use a while loop to add each grade[i] to total grade total. The value of i increases
in each iteration so that all variables are handled.
It is clear that the algorithm is trivial as long as we find a way to store and rep-
resent data of the same type. This also shows that the way data are organized and
represented is a crucial issue when solving problems with computers.

Case study 4 Complex table processing


Suppose there are four students, all of which take the same six courses. Write a pro-
gram that calculates average grades for each of them.
The only difference between this problem and the one earlier is the number of
grades. As shown in Figure 1.5, we can use a two-dimensional table to store data.
Its row index and column index uniquely identify a grade. For example, the grade
in row 1 column 2, whose value is 82, can be represented by grade[1][2].
1.1 Concept of arrays 5

Case study 4
Complex table processing

ID Course 1 Course 2 Course 3 Course 4 Course 5 Course 6 Average


1001 80 82 91 68 77 78
1002 78 83 82 72 80 66
1003 73 50 62 60 75 72
1004 82 87 89 79 81 92

Grade of student 1 in course 2 is


Column j grade[1][2]=82

grade[i][j] j=0 j=1 j=2 j=3 j=4 j=5


i=0 80 82 91 68 77 78
Row i i=1 78 83 82 72 80 66
i=2 73 58 62 60 75 72
i=3 82 87 89 79 81 92

Figure 1.5: Complex table processing.

We can use a for loop to process grades for a single student and use another
one to calculate average grades for all of them. The algorithm and code implemen-
tation will be given in the section of two-dimensional arrays.

1.1.2 Representation of data of the same type

The discussion earlier showed that a new mechanism is necessary to handle data of
the same type. With respect to data representation and processing, arrays are a
data structure that regularly expresses data so that they are processed regularly.
Since arrays are collections of variables whose names have a pattern, they are sup-
posed to have features of variables. Figure 1.6 compares arrays with plain variables.

Plain variable Array Notes


• Memory is allocated upon
To be determined, but it should definition
Definition type name; consists of: type, name, number of
variables • Size of memory allocated is
determined by variable type
Each storage unit of an array
Quantity One Multiple
has the same size
Storage
unit Length sizeof(type) sizeof(type)* number of variables Length is measured in bytes
Address &name To be determined
Referencing method name name[index]
It is easier to process in
Initialization type name=value To be determined programs if variables are
initialized

Figure 1.6: Comparison of a group of variables with a single variable.


6 1 Arrays

During the definition of a plain variable, the system allocates memory according to
its type specified by programmers. The definition of an array consists of type, name
and, in particular, the number of variables in the array.
There are multiple variable values in an array, so they should be stored in mul-
tiple storage units, whose sizes depend on types of the variables. The size of a stor-
age unit is measured in bytes and can be computed using the sizeof operator.
Besides, a referencing method of the address of a storage unit is necessary so
that programmers can inspect the unit.
We can infer from the examples earlier that the referencing method of variable
values in an array is to use the array name with an index.
Moreover, we should be able to initialize an array since we can do the same
with plain variables. Hence, a corresponding syntax is necessary.

1.2 Storage of arrays

There are four issues related to array storage, namely definition, initialization, mem-
ory allocation, and memory inspection.

1.2.1 Definition of arrays

1.2.1.1 Definition of arrays


An array is a collection of data of the same type. Figure 1.7 shows how to define an
array, where a definition is constructed by a type identifier followed by an array
name and multiple constants inside square brackets. Each constant indicates the
number of variables in the corresponding dimension.

Arrays

An array is a collection of data of the same type. Memory is allocated


upon definition, which
Syntax remains unchanged
during execution
type name [ constant 1 ][constant 2] ……[constant n];

E.g.
Number of Number of Memory size
Definition Type Name
dimensions variables
int x[ 100 ] int x 1 100 100* sizeof(int)
char c[2][3] char c 2 2*3 2*3* sizeof(char)

Figure 1.7: Definition of arrays.


1.2 Storage of arrays 7

In the figure above, the first row defines a one-dimensional integer array x with 100
variables. To compute the size of its memory space, we can obtain the size of its
type using the sizeof operator and multiply it with the number of variables. The second
row defines a two-dimensional character array with two rows and three columns. In
other words, it has six variables in total. The array name is c.

1.2.1.2 Reference of array elements


C uses a special term for variables in an array: array elements. An array element is
used in the same way as a single variable. To reference an array element, we use
the array name suffixed by an index wrapped in square brackets.

Think and discuss Do contents inside square brackets in an array definition and an element ref-
erence refer to the same thing?

Discussion: The index of an array element is a numerical expression, which indicates the posi-
tion of the element in an array; the object inside square brackets in an array definition has to
be a constant, which indicates the number of elements in the corresponding dimension. It is
worth noting that the number of elements must not be a variable. Like plain variables, arrays
obtain memory space from the system during array definition. The size of the allocated space
does not change during execution once the array is defined. Such a way of memory utilization
and management is called static memory allocation. On the other hand, C also provides “dy-
namic memory allocation,” which will be introduced in examples in chapter “Functions”.
Indices of array elements in C must start from 0. Accessing an array out of bound leads to a
logic error, but it is not a syntax error.
For example, the one-dimensional array x defined in Figure 1.8 has 100 elements with an
index range 0 to 99. If we try to access an element outside this range, we are accessing the
array out of bound. Grammatically, it is equivalent to using undefined variables.

Array elements

An array element is a variable with subscript in an array.


Array elements are used in the same way as variables.
Do contents inside
Referencing syntax square brackets in an
array definition and in an
name [index 1] [index 2] …… [index n] element reference refer
to the same thing?
Array indices

Array indices should be numerical expressions; they start from


0; programmers should not access indices that are out of bound

E.g.
Definition Index range Correct usage Out of bound examples
int x[ 100 ] [0]~[99] x[0], x[6], x[99] x[-1], x[100]

Figure 1.8: Array elements and their referencing rules.

The reason that out-of-bound errors are not syntax errors is that the compiler will not check whether
the index is valid. As a result, programmers should take care of indices when using arrays.
8 1 Arrays

Knowledge ABC Index out-of-bound errors


An index out-of-bound error happens when accessing an array element whose index does not
fall in the predefined index range. C compilers seldom check whether indices are valid. Accessing
an index that is out of bound leads to the following issues.
First, although reading an out-of-bound element does not change values in memory, the cal-
culation that uses this value will generate wrong results.
Second, writing to an out-of-bound element does change values in memory. If the memory
units we write to contain values of other variables, the program may also generate wrong re-
sults. Furthermore, it is tough to debug in this case, since we do not know when the modified
value gets referenced.
An index out-of-bound error may occur in arrays and pointers that point to arrays. It is one of
the most common mistakes that beginners may make, so we should be careful when using arrays.

Having learned how to define arrays and how to reference array elements, we can
complete the program for number reversing problem.

01 int main(void )
02 {
03 int i;
04 int x[100]; // Array definition
//x[i] references array elements, the index is an expression
05 for ( i=0;i<100; i++) scanf ("%d", &x[i] );
06 for ( i=99; i>=0; i-- ) printf ("%d", x[i] );
07 return 0;
08 }

Line 4 contains definition of an array. Note how we reference array elements on line
5 and line 6.
Indices in square brackets on line 5 and 6 are variables, which are special forms
of expression. They start from 0 and end at 99.
Grammatically, the index of an array element should be a numerical expression
and the index of the first element of an array must be 0.

1.2.1.3 Storage characteristics of arrays


The system allocates contiguous memory space to an array based on its defini-
tion, so the storage characteristics can be summarized as “memory is allocated
during definition, the size keeps unchanged during execution, and elements are
stored continuously”.
Figure 1.9 shows an array definition written by a student. Will the memory be
allocated to array a in this case?
1.2 Storage of arrays 9

Array memory space


memory is allocated during definition, the size keeps unchanged
during execution, elements are stored continuously

E.g. Will memory be


int x; int x=100; allocated to array
int a[x]; int a[x]; a in this case?

Figure 1.9: Storage characteristics of arrays.

1.2.1.4 Comparison of variables of the same type with plain variables


With the rules of arrays in C, we can update the table in Figure 1.6 and obtain
Figure 1.10.

Plain variable Array Notes


Number of dimensions
1 Definition type name; type name [constant]…[constant] of an array is equal to
number of indices
2 Name Variable name Array name Identifiers

Array elements are of


3 Variable One A group
the same type

Quantity One Multiple Elements in an array


are stored
Storage Length sizeof(type) sizeof(type) * number of variables consecutively
4
unit
Allocated by the
Address &name name
system
5 Referencing method name name[index]…[index] Number of dimensions
type name[constant] …[constant] of an array is equal to
6 Initialization type name=value = { a group of initial values} number of indices

Figure 1.10: Comparison of arrays with plain variables.

(1) Number of dimensions of an array is determined by the number of indices, that


is, the number of pairs of square brackets. The constant in square brackets indi-
cates the number of elements in an array.
(2) Array names are identifiers.
(3) Values of array elements are of the same type.
(4) When allocating memory space for an array, C allocates a continuous space for
all elements and defines that the array name refers to the beginning address of
the memory allocated. In other words, array names are addresses.
(5) Array elements are accessed by array name with index.
(6) Initialization is done during definition. The syntax of initialization requires curly
brackets.
10 1 Arrays

1.2.2 Initialization of arrays

We can modify the keyboard input part in the code implementation of the number
reversing problem so that the array is initialized with values. The revised program
is as follows:

01 int main(void )
02 {
03 int i; //Defines an array and initializes array elements
04 int x[10]={1,2,3,4,5,6,7,8,9,10};
05 //for ( i=0;i<10; i++) scanf ("%d", &x[i] );
06 for ( i=9; i>=0; i-- ) printf ("%d", x[i] );
07 return 0;
08 }

Statement on line 4 defines the array and initializes array elements, so the keyboard
input assignment can be skipped.
What is the advantage of initializing an array? If we have to debug the program
multiple times, it is more efficient to initialize the array than typing in numbers
repeatedly.
Array initialization defines an array and initializes its elements at the same time.
There are three ways to initialize an array in C, as shown in Figure 1.11.

Array initialization
An array initialization defines an array and initializes its elements at the same time

E.g. Case Example Array Notes


size
int m[5]= {1,3,5,7,9} 5
1 Initialize all elements A 2-d array is stored in a
int a[2][3] = { {1,3,5}, {2,4,6}}; 2 by 3
row-first manner

int b[5] = {1,3,5} 5 Uninitialized elements are


2 Initialize some elements set to 0 automatically by
int x[ 100 ] ={ 1,3, 5, 7 }; 100 the system

int n[ ] = {1,3,5,7,9} 5
Array size determined by
3 String termination mark ‘\0’
number of initial values char c[ ] =“abcde”; 6
is also an element

Figure 1.11: Array initialization.

1.2.2.1 Initialize all elements


In the first case in Figure 1.11, the one-dimensional array m has five elements and
five values are assigned to the array. The two-dimensional array a has two rows and
1.2 Storage of arrays 11

three columns, so it consists of six elements. Note that how curly brackets are used
when assigning all six values.

1.2.2.2 Initialize some elements


In the second case, the length of array b is 5, but only the first three elements are
initialized with a value. The other elements are automatically initialized with 0 by
the C language system.

1.2.2.3 Array size determined by number of initial values


We can omit the array size in square brackets when defining arrays. The size can be
determined by the system based on the number of initial values. In particular, C al-
lows us to assign initial values to character arrays with strings. Note that the string
termination mark ‘\0’ is an element as well.

1.2.3 Memory layout of arrays

We will introduce the memory layout of arrays through examples.

1.2.3.1 Memory layout of one-dimensional arrays


A one-dimensional array x of size 100 is defined in Figure 1.12. Indices start from 0
and end at 99. The first four elements are initialized with initial values, while the
rest are 0. These elements are stored contiguously in the order of index, that is,
from x[0] to x[99].

C defines that array elements


int x[ 100 ]={ 1, 3, 5, 7 }; are stored consecutively in
the order of indices
Index 0 1 2 3 4 … i … 98 99
Element value 1 3 5 7 0 0 0 0 0 0
Element storage order x[0] x[1] x[2] x[3] x[4] x[i] x[98] x[99]

Figure 1.12: Memory layout of one-dimensional array.

1.2.3.2 Memory layout of two-dimensional arrays


As shown in Figure 1.13, two-dimensional array a has two rows and three columns.
Its elements are stored in a row-first manner.
The 0th row is initialized with 1, 3, and 5, while the first row is initialized with 2,
4, and 6. The 0th row is stored first, followed by the first row. Note that a[0] denotes
12 1 Arrays

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


C defines that the 1 -
0 1 2 dimensional form of a 2 -
dimensional array
a[0] → 0 1 3 5
denotes “row address”
a[1] → 1 2 4 6

Row address a[0] a[1]


Element
a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2]
storage order
Element value 1 3 5 2 4 6

Figure 1.13: Memory layout of two-dimensional array.

the beginning position of the 0th row and a[1] denotes the beginning position of the
first row.
C defines that the one-dimensional form of a two-dimensional array which de-
notes “row address”.

1.2.4 Memory inspection of arrays

With the help of IDE, we can inspect how arrays are stored in the memory. We shall
start from cases where arrays are initialized. The program is as follows:

01 //Use an initial value list to initialize arrays


02 #include <stdio.h>
03 int main(void)
04 {
05 // Use an initial value list to initialize arrays
06 int m[5]= {1,3,5,7,9};
07 int n[ ] = {2,4,6,8};
08 int x[8] = {1,3,5,7};
09 char c[ ] ="abcde";
10 int a[2][3] = { {1,3,5}, {2,4,6}};
11 int i, j;
12
13 //Output 1-dimensional array m as a list
14 printf( "1-dimensional array m[5]\n");
15 printf( "%s%13s\n", "Element", "Value" );
16 for ( i = 0; i < 5; i++ )
17 {
18 printf( "%6d%13d\n", i, m[ i ] );
19 }
20 printf( "\n");
21
1.2 Storage of arrays 13

22 // Output 2-dimensional array m as a list


23 printf( "2-dimensional array a[2][3]\n");
24 for (i = 0; i < 2; i++) //Row index range
25 {
26 for (j = 0; j < 3; j++) //Column index range
27 {
28 printf( "%d ", a[i][j] );
29 }
30 printf( "\n");
31 }
32 return 0;
33 }

On line 6, we define an integer array m of size 5 and initialize it. If we type in the
array name m in the Watch window, we can see the beginning address of the array
and values of each element, as shown in Figure 1.14.

m n c

x a
String termination
mark \‘0’ is
automatically
inserted by the
system

Figure 1.14: Inspecting memory of array 1.

On line 7, we define an integer array n without specifying the size and initialize it
with four initial values. We can see that 4 memory units are allocated to it.
On line 8, we define an integer array x of size 8 and partially initialize it. It is
clear that the uninitialized elements are set to 0 by the system.
On line 9, we define a character array c without specifying the size and initialize
it with a string of five characters. The system allocates six storage units, where the
last one has value 0. This is the string termination mark inserted by the system
automatically. It also takes up one storage unit.
On line 10, we define a 2 by 3 two-dimensional array a and initialize it. Each row
of the array has a beginning address, where the address of the first row is also the
beginning address of the entire array.
14 1 Arrays

On line 15, the table header is printed.


On lines 16–19, we use a for loop to output index i and corresponding array
elements m[i].
Program result:

1-dimensional array m[5]


Element Value
0 1
1 3
2 5
3 7
4 9
2-dimensional array a[2][3]
1 3 5
2 4 6

Knowledge ABC Differences between ‘\0’, ‘0’, “0” and 0 in C


Characters are stored as their ASCII values in C. Each character takes up 1 byte. The first value
in the ASCII table is 0, which corresponds to character Null, namely ‘\0’. It is used as the termi-
nation mark of strings and is inserted to the end of strings automatically by the system.
Character ‘0’ has ASCII value 48 or 0 × 30 in hexadecimal form. To convert a number into the
corresponding character in a program, for example, converting number 8 into character 8, we
can write 8+‘0’ in the code.
The character ‘0’ is a character literal, while number 0 is an integer literal. They are different
objects and are stored in different ways in computers. Character literals can be used as integers
in computation.
The difference between “0” and ‘0’ is that “0” is a string literal while ‘0’ is a character literal.
They are completely different. Character literals are wrapped by single quotation marks while
string literals use double quotation marks. A character literal has to be a single character, while
a string literal can have more than one character.

The output of two-dimensional array a is implemented by two for loops.


On line 24, the first for loop iterates through row index i, which has range 0 to 1.
On line 26, the second for loop iterates through column index j, which has range
0 to 2.
In Figure 1.15, we can see that j traverses the range 0 to 2 when i is 0, and tra-
verses the range again when i is 1.

0 1 2 Row i 0 1
a[0] → 0 1 3 5 Column j 0 1 2 0 1 2
a[1] → 1 2 4 6 a[i][j] 1 3 5 2 4 6

Figure 1.15: Inspecting memory of array 2.


1.2 Storage of arrays 15

When defining an array, the system allocates contiguous memory space to


store its elements based on the array type and number of elements. It is shown in
the Memory window that int n[4] takes up a continuous block of memory with
size 4*4 bytes (in a 64-bit compiling environment, type int takes up 4 bytes,
which can be verified by subtracting addresses of two array elements), as illus-
trated in Figure 1.16.

Address Value Variable


18FF24 2 n[0]
18FF28 4 n[1]
18FF2C 6 n[2]
18FF30 8 n[3]

Figure 1.16: Continuous storage of a one-dimensional array.

Similarly, int a[2][3] takes up a continuous block of memory with size 6*4 bytes, as
shown in Figure 1.17.

Row Address Value Variable Row address


18FF0C 1 a[0][0]
a[0]
Row 0 18FF10 3 a[0][1]
18FF0C
18FF14 5 a[0][2]
18FF18 2 a[1][0]
a[1]
Row 1 18FF1C 4 a[1][1]
18FF18
18FF20 6 a[1][2]

Figure 1.17: Continuous storage of a two-dimensional array.

Note that the array name refers to the address of the entire array, which is also the
beginning address of the array.
With rules of storage and elements referencing, we may now process data in
arrays.
16 1 Arrays

1.3 Operations on one-dimensional arrays

Example 1.1 Highest score problem


1. Problem description
In the scoring problem we have seen before, there was a step where the highest score was dis-
carded. This is equivalent to finding the maximum of a series of numbers.

2. Algorithm description
We have seen this problem in section “representation of algorithms”, where the scores were
read from keyboard input. Now we can store scores given by referees in an array score[10]. The
algorithm can then be updated accordingly, as shown in Figure 1.18.

Top-level pseudo code First refinement Second refinement


Counter i=0;
Use score[0] as Largest
Largest=score[0];
Find the highest one of while counter i< 10;
scores stored in array Compare each element in if(Largest < score[i])
score[10] array score with Largest,
Store the larger in Largest; Largest=score[i];
i increases by 1;
Output Largest Output Largest;

Figure 1.18: Eliminating the highest score using an array.

In the second refinement, a counter i is used to record the number of comparisons. Variable
Largest is initialized with score[0]; then, Largest is compared with score[i] repeatedly and up-
dated with the larger value in the loop body. Once the loop is done, Largest is printed.

3. Code implementation
01 //Finding the maximum number in an array
02 #include <stdio.h>
03 #define SIZE 10
04
05 int main(void)
06 {
07 int score[SIZE]
08 = {89,92,97,95,90,96,94,92,90,98};
09 int i; //Counter
10 int Largest =score[0]; //Initialize Largest with score [0] as a comparison basis
11 for ( i = 0; i < SIZE; i++ )
12 {
13 if (Largest < score[i])
14 Largest=score[i]; //Find the maximum
15 }
16 printf( "The highest score is %d\n", Largest );
17 return 0;
18 }
1.3 Operations on one-dimensional arrays 17

Program result:
The highest score is 98

Note: the score array is initialized on line 8 so that testing becomes easier.
On lines 11–15, the for loop finds the largest value and stores it in variable Largest.
Based on this program, it is trivial to write a program that finds the minimum number. Now we
can discard both the highest score and the lowest score by replacing them with 0.

4. Debugging
One should carefully design test cases for inspection or verification. Critical points in the de-
bugging of the earlier program are shown in Figure 1.19.

Debugging
plan 11 for ( i= 0; i< SIZE; i++ )
12 {
– Inspect memory layout of 1-d array
13 if (Largest < score[i])
– Reference of array elements
14 Largest=score[i];
– Use breakpoints to find required values quickly
// Find the maximum
15 }

Figure 1.19: Debugging the “eliminating highest score” program.

Figure 1.20 shows the score array in the Watch window. There are 10 elements, each of which
are initialized with an initial value. The maximum value Largest is initialized with the value of
score[0], which is 89.

Figure 1.20: Memory inspection of a one-dimensional array 1.

In Figure 1.21, the condition of if statement in the for loop evaluates to false when i = 0, so
Largest keeps unchanged.
18 1 Arrays

Figure 1.21: Memory inspection of a one-dimensional array 2.

In Figure 1.22, i becomes 1 after increment and score[1] = 92.

Figure 1.22: Memory inspection of a one-dimensional array 3.


1.3 Operations on one-dimensional arrays 19

In Figure 1.23, Largest becomes 92 when i = 1.

Figure 1.23: Memory inspection of a one-dimensional array 4.

In Figure 1.24, we insert a breakpoint in the line pointed by the yellow arrow to inspect pro-
gram execution conveniently. Using the Go command, we can interrupt the program at this
statement whenever the condition of if statement evaluates to true. Here i = 2 and score[2] has
value 97, which is larger than the value of Largest, 92.

Figure 1.24: Memory inspection of a one-dimensional array 5.

In Figure 1.25, we execute the Go command and the program pauses again. Now, i = 9 and
score[9] has value 98, which is larger than the value of Largest, 97.
20 1 Arrays

Figure 1.25: Memory inspection of a one-dimensional array 6.

In Figure 1.26, the loop terminates and the final value of Largest is 98.

Figure 1.26: Memory inspection of a one-dimensional array 7.

Example 1.2 Computing total score


Scores given by judges are stored in an array score[10].

[Analysis]
1. Algorithm design
The algorithm is shown in Figure 1.27. Code implementation can be easily adapted from the pseudo
code in the second refinement.
1.3 Operations on one-dimensional arrays 21

Top-level pseudo code First refinement Second refinement


Use total to store the sum ,and Initialize score[10]
score[10] to store scores Sum total =0;
Compute sum of scores while (i<10)
stored in array score[10] Add values of elements in score total += score[i];
to total repeatedly
i++;
Output result Output total

Figure 1.27: Computing total score.

After eliminating the highest score and the lowest score, we can compute the total score that
complies with the scoring rule.
2. Code implementation
01 //Compute sum of array elements
02 #include <stdio.h>
03 #define SIZE 10
04
05 int main(void)
06 {
07 int score[ SIZE ] = {98,92,89,95,90,96,94,92,90,97};
08 int i; //counter
09 int total = 0; //sum
10
11 for ( i = 0; i < SIZE; i++ )
12 {
13 total +=score[ i ]; //Compute sum of array elements
14 }
15 printf( "The total score is %d\n", total );
16 return 0;
17 }

Program result:
The total score is 933

Example 1.3 Number guessing game


An array stores an increasing number sequence 5, 10, 19, 21, 31, 37, 42, 48, 50, 55. Use binary
search to find elements with key values 19 and 66.

[Analysis]
1. Algorithm analysis
Let low denote the position of the minimum value in the searching range, and high denote the
position of the maximum value in the searching range. The comparison position in binary search
is then mid = (low + high)/2. Comparing key value with the element at position mid yields one of
the following results:
– Equal: the element at position mid is what we are looking for.
– Greater: we will look for the element in the lower range by setting low = mid + 1.
– Less: we will look for the element in the higher range by setting high = mid – 1.
22 1 Arrays

Figures 1.28 and 1.29 illustrate processes of finding values 19 and 66.

Search for
19

R[] 5 10 19 21 31 37 42 48 50 55
Position 0 1 2 3 4 5 6 7 8 9

low mid high


Now mid=5, R[mid] . key=37> k, we proceed in range R[0…4]

R[] 5 10 19 21 31 37 42 48 50 55
Position 0 1 2 3 4 5 6 7 8 9

low mid high

Now mid=2, R[mid] . key=19=k, the search succeeded

Figure 1.28: Binary search: searching for k = 19.

Search for
66
R[] 5 10 19 21 31 37 42 48 50 55
Position 0 1 2 3 4 5 6 7 8 9

low mid high


Now mid=5, R[mid].key=37<k, we proceed in range R[6…9]

R[] 5 10 19 21 31 37 42 48 50 55
Position 0 1 2 3 4 5 6 7 8 9

low mid high


Now mid=8, R[mid].key=50<k, we proceed in range R[9…9]

R[] 5 10 19 21 31 37 42 48 50 55
Position 0 1 2 3 4 5 6 7 8 9

low mid
Now mid=9, R[mid].key=55<k, we proceed in range
R[10…9].Because low>high, the search failed.

Figure 1.29: Binary search: searching for k = 66.


1.3 Operations on one-dimensional arrays 23

2. Code implementation
#include <stdio.h>
#define N 10
int main(void)
{
int a[N]={5,10,19,21,31,37,42,48,50,55};
int low=0, high=N-1,mid;
int key;
int flag=0; //Search flag, 0=fail, 1=success
printf("Please enter number to search:");
scanf("%d",&key);
while (low<=high) //Search range is not empty
{
mid = (low+high+1)/2;
if (a[mid]== key) //Match
{
flag=1;
break;
}
else
{
if (a[mid]> key) high = mid-1; //Continue searching in lower range
else low = mid+1; // Continue searching in higher range
}
}
if (flag==1)
printf("Search succeeded, index of %d is %d\n",key,mid);
else
printf("Search failed\n");
return 0;
}

Example 1.4 Assign values to a one-dimensional array using loop


Find the first 20 entries of the Fibonacci sequence.
The Fibonacci sequence is as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . . Its recurrence equation is
F(0) = 0, F(1) = 1,
F(n) = F(n–1) + F(n–2)

[Analysis]
1. Data structure design
Since indices and values in the Fibonacci sequence are 1-to-1 corresponded, we can store values
into a one-dimensional integer array, which will be represented by int f[20] in this example.
2. Algorithm design
We shall construct the first 20 entries based on the recurrence equation of the Fibonacci se-
quence, store them into the array and eventually output them.
24 1 Arrays

The algorithm is shown in Figure 1.30.

Top-level pseudo code First refinement Second refinement


Initialize array [20] int f[20]={ 0, 1 }
with the first two values i=2;
of the sequence
Store result in an array of while i< 20
size 20 and output result Fill in the array using
the recurrence relation f [i] = f [i-1]+f [i-2];
starting from f[2] i++;
Output result Output elements in array f

Figure 1.30: Computing values of Fibonacci sequence.

3. Code implementation
1 //Find first 20 entries in Fibonacci sequence
2 #include <stdio.h>
3 int main(void)
4 {
5 int i;
6 int f[20]={0, 1}; //Array initialization
7
8 for (i=2; i<20; i++) //Generate the sequence
9 {
10 f[i]=f[i-1]+f[i-2]; //Recurrence equation of Fibonacci equation
11 }
12 for (i=0; i<20; i++) //Output array elements
13 {
14 if (i%5==0) printf("\n"); //Print 5 entries on each line
15 printf("%8d", f[i]);
16 }
17 return 0;
18 }

Program result:
0 1 1 2 3
5 8 13 21 34
55 89 144 233 377
610 987 1597 2584 4181

4. Program analysis
We shall analyze characteristics of iterated data processing by reading the program.
Lines 8–11 insert values into the Fibonacci array. Let the index be i, which corresponds to
array element f[i]. We can construct a table for them and fill in it with their values, as shown in
Figure 1.31. In addition to dynamic tracing and debugging, a static approach like this can also
help us analyze patterns in program execution. Note that indices start from 0, so the index of
the last element should be one less than the array size.
1.3 Operations on one-dimensional arrays 25

Index i 0 1 2 3 4 5 … 18 19 20
f[i] 0 1 2 3 5 8 … … … …

Figure 1.31: Analysis of Fibonacci sequence program.

5. Discussion
(1) What if we do not initialize array f?
Discussion: If so, values of f[0] and f[1] will be arbitrary values, so further computation
will be wrong.
(2) How can we construct the Fibonacci sequence of arbitrary size?
Discussion: We can make the array size a symbol constant, so the program can be easily
adapted.
(3) What if we change the execution condition of the first for loop (line 8) to i ≤ 20?
Discussion: An out-of-bound error will happen because we are going to write to f[20],
which is not in the range of the array. This is a logic error in the program.

Program reading exercise


Teacher review system statistics
The university Mr. Brown works for has built an online teacher review system, where students
can rate teachers with a score in the range 6–10. Suppose we have randomly collected 50 rat-
ings of a teacher and stored them into an array, please write a program that generates number
of occurrences of each possible score.

1. Algorithm description
Let the ratings array be rating[ ]. It records number of occurrences of each score. The index i can
be computed by subtracting 6 from score x (6 ≤ x ≤ 10), that is, i = x–6, so we can use values
score–6 as indices of the ratings array. Whenever we find a new occurrence of a certain score,
we add one to the corresponding array element.

2. Code implementation
1 #include<stdio.h>
2 #define RESPONSE_NUM 50 //Size of review array
3 #define RATING_SIZE 5 //Size of ratings array
4
5 int main(void)
6 {
7 int answer; //Counter
8 int counter;
9
10 int rating[RATING_SIZE]={0}; //Rating array
11 int responses[RESPONSE_NUM] //Review array that stores students’reviews
12 ={ 6,8,9,10,6,9,8,7,7,10,6,9,7,7,7,6,8,10,7,
13 10,8,7,7,6,7,8,9,7,8,7,10,6,7,6,7,7,10,8,
14 6,7,7,8,6,6,7,8,9,7,7,10
15 };
16
26 1 Arrays

17 //Use score-6 as index of rating array, add 1 to an element if we find new


18 //occurrence of the corresponding score
19 for (answer=0; answer<RESPONSE_NUM; answer++)
20 {
21 rating[ responses[answer] -6 ]++;
22 }
23
24 //Print result in a table
25 printf("%s%17s\n","Rating","Number of occurrences");
26 for (counter=0; counter<RATING_SIZE; counter++)
27 {
28 printf("%6d%17d\n",counter+6,rating[counter]);
29 }
30 return 0;
31 }

Program result:
Rating Number of occurrences
6 10
7 19
8 9
9 5
10 7

1.4 Operations on two-dimensional arrays

Having seen operations on one-dimensional arrays, we can proceed to two-dimensional


arrays.

Example 1.5 Finding maximum in a two-dimensional array


There were three groups in Mr. Brown’s class, each with six students. Now that the final exam
has finished, please write a program to find the highest score and the corresponding student.

[Analysis]
1. Data description
As shown in Figure 1.32, we can store the scores in a two-dimensional array.
Essentially, this problem is equivalent to finding the maximum value in a two-dimensional
array with N rows and M columns and its row and column indices. To do this, we can simply
repeat the process of finding the maximum value in a one-dimensional array N times.
Figure 1.33 shows how row and column indices change when traversing the array in a row-
first manner. We first traverse row 0, with column index changing from 0 to M–1. Then we tra-
verse row 1, with column index changing from 0 to M–1 as well. We repeat this process until we
reach row N–1.
1.4 Operations on two-dimensional arrays 27

Group Grade
1 80 77 75 68 82 78
2 78 83 82 72 80 66
3 73 50 62 60 91 72

Figure 1.32: Exam results.

Column
0 1 2 3 4 5
Row
0 80 77 75 68 82 78
1 78 83 82 72 80 66
2 73 50 62 60 91 72

Changes of row and column values when


traversing in a row-first manner
Row i 0 1 … N-1
Column j 0~M-1 0~M-1 … 0~M-1

Figure 1.33: Traversing order of two-dimensional arrays.

2. Algorithm description
Figures 1.34 and 1.35 show the pseudo code of the algorithm.

Top-level pseudo code First refinement


Input 2-d array Input 2-d array
Use the first element as comparison basis max
Find the maximum element and Compare each element (row-first manner)with max,
its row and column indices Update max with the larger
Record the corresponding indices line and col
Output result Output result

Figure 1.34: Pseudo code of finding maximum value in two-dimensional array 1.


28 1 Arrays

Second refinement third refinement


Input 2-d array a[N][M] in a int i, j, a[N][M], max, line, col;
row-first manner(or initialize) for(i=0;i<N;i++)
for(j=0;j<M;j++)
scanf( "%d", &a[i][j] );
max=a[0][0]; line=col=0; max=a[0][0]; line=col=0;
i=j=0;
while row index i<N for(i=0;i<N;i++)
while column index j<M for( j=0;j<M;j++)
if ( max<a[i][j]) if (max<a[i][j])
max=a[i][j] {
line=i max=a[i][j];
col=j line=i;
j++; col=j;
i++; j=0; }
Output max,line and col printf(“\n max=%d\t line=%d\t col=%d\n”, max, line, col);

Figure 1.35: Pseudo code of finding maximum value in two-dimensional array 2.

3. Code implementation
We can write the code based on the second refinement, in which we use for statements to
implement while loops. The complete code is as follows:

01 #include <stdio.h>
02 #define N 3
03 #define M 6
04
05 int main(void)
06 {
07 int i,j,max,line,col;
08 int a[N][M]= { {80,77,75,68,82,78},
09 {78,83,82,72,80,66},
10 {73,50,62,60,91,72}
11 };
12 max=a[0][0];
13 line=col=0;
14 for (i=0; i<N; i++)
15 {
16 for ( j=0; j<M; j++)
17 {
18 if (max<a[i][j])
19 {
20 max=a[i][j];
21 line=i;
22 col=j;
23 }
24 }
25 }
26 printf("max=%d\t line=%d\t col=%d\n",max,line,col);
1.4 Operations on two-dimensional arrays 29

27 return 0;
28 }

Program result:
max=91 line=2 col=4。

4. Debugging
Based on the characteristics of two-dimensional arrays and key points of this problem, we
designed a few test cases for debugging, as shown in Figure 1.36.

18 if(max<a[i][j])
Debugging 19 {
plan 20 max=a[i][j];
• Inspect memory layout of 2-d array 21 line=i;
• Pattern of row and column indices 22 col=j;
• Use breakpoints to find required values quickly 23 }

Figure 1.36: Key points of debugging the program that finds maximum value in a two-dimensional
array.

One may notice that the row addresses of a two-dimensional array are represented in the form of
a one-dimensional array in the IDE debugger, as shown in Figure 1.37. To traverse the entire array,
we traverse every column for each row. Note that a two-dimensional array is stored row by row in
memory (each row as a one-dimensional array).

Row address reference


of 2-d array

Address Row 0 1 2 3 4 5
a[0] 0x18feec 0 80 77 75 68 82 78
a[1] 0x18ff04 1 78 83 82 72 80 66
a[2] 0x18ff1c 2 73 50 62 60 91 72

Pattern of row and column indices


Row I 0 1 … N-1
Column j 0~M-1 0~M-1 … 0~M-1

Figure 1.37: Data storage in finding maximum in two-dimensional array problem.


30 1 Arrays

As shown in Figure 1.38, we insert one breakpoint to the line where the current maximum
value is updated and to the line where the result gets printed. When the program enters the
first loop, as shown in Figure 1.39, the 0th element of the array is selected as the comparison
basis, whose value is a[0][0] = 80. In Figure 1.40, the program pauses after we execute the Go
command. The value of the element with index i = 0 and j = 4 is 82, which is larger than max.

Figure 1.38: Debugging the program that finds maximum in two-dimensional array 1.

Figure 1.39: Debugging the program that finds maximum in two-dimensional array 2.
1.4 Operations on two-dimensional arrays 31

Figure 1.40: Debugging the program that finds maximum in two-dimensional array 3.

In Figure 1.41, the program pauses after we execute the Go command. The value of the element
with index i = 1 and j = 1 is 83, which is larger than max.

Figure 1.41: Debugging the program that finds maximum in two-dimensional array 4.

In Figure 1.42, the program pauses after we execute the Go command. The value of the element
with index i = 2 and j = 4 is 91, which is larger than max.

Figure 1.42: Debugging the program that finds maximum in two-dimensional array 5.

In Figure 1.43, the program completed scanning the array, and the loop is terminated. Now, i = 3,
j = 6, and the maximum value of the array is max = 91.
32 1 Arrays

Figure 1.43: Debugging the program that finds maximum in two-dimensional array 6.

Conclusion Execution order of nested loops


As shown in Figure 1.44, C has the following rules for executing nested loops:
1. Check the outer loop execution condition: if it is met, the body of the outer loop is exe-
cuted; otherwise, the outer loop is terminated.
2. Check the inner loop execution condition: if it is met, the body of the inner loop is exe-
cuted; otherwise, the inner loop is terminated, and the program proceeds to loop incre-
ment of the outer loop.

Program reading exercise Whac-A-Mole


Whac-A-Mole is a classic computer game, in which moles pop up from holes at random. Players
need to force them back to their holes and obtain rewards by using a mallet to hit the moles on the
head.

Outer loop F
condition

T
1 for(i=0;i< N;i++)
2 { Inner loop F
3 for( j=0;j< M;j++) condition
4 { T
5 if (max<a[i][j])
Outer Inner loop body
6 { max=a[i][j]; Inner loop
7 line=i; loop
Inner loop
8 col=j;}
increment
9 }
10 } Outer loop
increment

Figure 1.44: Execution order of nested loops.


1.4 Operations on two-dimensional arrays 33

1. Algorithm description
The program uses random functions srand and rand to generate positions at which moles ap-
pear. The following Whac-A-Mole program has a 3 by 3 “ground” and treats user input coordi-
nates as positions the mallet hits. Although it is a console program and has a simple user
interface, the way it works is the same as a Whac-A-Mole game with beautiful graphics.

2. Code implementation
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//To simplify the code, we omitted curly brackets for some of the if-else statements
int main(void)
{
int times = 0; //Number of chances
int mousey = 0; //Row index of the mole
int mousex = 0; //Column index of the mole
int posy = 0; //Row index of the mallet
int posx = 0; //Column index of the mallet
int hits = 0; //Number of hits
int missed = 0; //Number of misses
int num = 0, row = 0, col = 0;
srand(time(0));
//Obtain game chances
printf("How many times do you want to play?:");
scanf("%d", &times);
//Print the map
printf("***\n***\n***\n");
printf("Mallet position input should be row index followed by column index, separated by
space\n");
//Actual game process
for (num = 1;num <= times;num++)
{
//Obtain position of mole and mallet
mousey = rand() % 3 + 1;
mousex = rand() % 3 + 1;
do
{
printf("Enter mallet position:");
scanf("%d %d", &posy, &posx);
} while (posy < 1 || posy > 3 || posx < 1 || posx > 3);
//Update number of hits and misses
if (mousey == posy && mousex == posx) hits++;
else missed++;
//Print the map
for (row = 1;row <= 3;row++)
{
for (col = 1;col <= 3;col++)
{
34 1 Arrays

if (row == posy && col == posx) printf("O");


else if (row == mousey && col == mousex) printf("X");
else printf("*");
}
printf("\n");
}
//Text indicating hit or miss
if (mousey == posy && mousex == posx) printf("Bingo!\n");
else printf("You missed.\n");
//Print total score
printf("%d hits,%d misses\n", hits, missed);
}
return 0;
}

Program reading exercise Determining nationality


Six people are staying at a hotel, each from a different country. These countries are America,
Germany, Britain, France, Russia, and Italy. We shall use letters A to F to denote these people. It
is known that:
(1) A and the American are doctors.
(2) E and the Russian are technicians.
(3) C and the German are technicians.
(4) B and F used to be soldiers, and the German has never been a soldier.
(5) The French is older than A; the Italian is older than C.
(6) B and the American are going to Xi’an next week, while C and the French are going to
Hangzhou next week.

Determine the nationalities of these people.

[Analysis]
1. Data analysis
We shall first use the given information to eliminate the wrong answers.
Based on conditions 1, 2, and 3, we can conclude that A is not American, E is not Russian,
and C is not German. Based on occupation limits (A and the German have different jobs, so do E
and the American, E and the German, C and the American, and C and the Russian), it is clear
that A is neither Russian nor German, E is neither American nor German, and C is neither
American nor Russian.
It can be inferred from conditions 4 and 5 that neither B nor F is German, A is not French, and
C is not Italian.
Given condition 6, we know B is neither American nor French (because B and the French are
going to different cities next week), and C is not French.
To sum up:
A: A is not American, Russian, German, or French.
B: B is not German, American, or French.
C: C is not German, American, Russian, Italian, or French.
D: no information.
E: E is not American or German.
F: F is not German.
1.4 Operations on two-dimensional arrays 35

We can store the earlier information into matrix a, and country names into another one-
dimensional array countries, as shown in Figure 1.45.
Rows of matrix a represent these guests, while columns represent their home countries. The
0th row is a special row for progress flags, which is either 1 for not processed or 0 for proc-
essed. The values of other elements indicate nationalities. For example, 4 represents Germany
in the countries array. If a value is 0, the person represented by the row does not come from the
country represented by the column.
2. Algorithm design
Following steps 2 and 3 in Figure 1.45, we can find the solution by repeatedly zeroing out rows.

0 1 2 3 4 5 6

Am Br Fr Ge It Ru
1
Column data process flag
0 1 1 1 1 1 1
1: not processed, 0:processed
1 A 0 2 0 0 5 0

2 B 0 2 0 0 5 6

3 C 0 2 0 0 0 0 3

4 D 1 2 3 4 5 6 Zero out other elements in row x

5 E 0 2 3 0 5 6

6 F 1 2 3 0 5 6
2
Find a column y with only one non-zero element
Counter num=1, row index x=4, column index y=4

0 1 2 3 4 5 6
American British French German Italian Russian

*countries[7] = {" ","American","British","French","German","Italian","Russian "}; }

Figure 1.45: Storage and procedures of determining nationalities problem.

3. Code implementation
#include<stdio.h>
char *countries[7]={" ","American","British","French","German","Italian","Russian"};
//The asterisk before countries indicates that the array stores addresses,
//which are beginning addresses of strings
int main(void)
{
int a[7][7],i,j,k,num,x,y;
for(i=0;i<7;i++) //Initialize the matrix
for(j=0;j<7;j++) a[i][j]=j; //Row for person, column for country,
//and value for nationality
for(i=1;i<7;i++) a[0][i]=1; //0-th element in each column is the progress mark,
//1 means not processed
//Enter know information, 0 means the person is not from a country
a[1][1] = a[1][3] = a[1][4] = a[1][6] = 0; // A is not American, Russian, German or French
a[2][1]= a[2][3]= a[2][4] =0; // B is not German, American or French
a[3][1] = a[3][3] = a[3][4]= a[3][5] =a[3][6] = 0;
// C is not German, American, Russian, Italian or French
36 1 Arrays

a[5][1] = a[5][4]= 0; // E is not American or German


a[6][4]=0; //F is not German
while(a[0][1]+a[0][2]+a[0][3]+a[0][4]+a[0][5]+a[0][6]>0)
//Jump out of the loop once every column is processed
{
for(i=1;i<7;i++) //i is column index, we process the matrix column by column
{
if(a[0][i]) //Process the column if it hasn’t been processed
{
for(num=0,j=1;j<7;j++) //j is row index
{
if(a[j][i])
{
num++; //num counts non-zero elements in the column
x=j;
y=i; //x and y are coordinates of the non-zero element
}
}
if(num==1) //If there is only one non-zero element,
//zero out the row (except the non-zero element)
{
for(k=1;k<7;k++)
{
if(k!=y)a[x][k]=0;
a[0][y]=0; //Set column y to be “processed”
}
}
}
}
}
for(i=1;i<7;i++) //Print result
{
printf("%c is",'A'-1+i); //Print person
for(j=1;j<7;j++)
{
if(a[i][j]!=0)
{
printf("%s\n",countries[a[i][j]]); //Print country
break;
}
}
}
return 0;
}

Program result:
A is Italian
B is Russian
1.5 Operations on character arrays 37

C is British
D is German
E is French
F is American

1.5 Operations on character arrays

Example 1.6 Password verification


When a user logs into a system, the system needs to compare the password he/she enters with
the one used for registration. For example, a user signed up with password abc24680, as
shown in Figure 1.46. How should the system store this password?

Index 0 1 2 3 4 5 6 7 8 9 ... 18 19
Registered
'a' 'b' 'c' '2' '4' '6' '8' '0'
password

Figure 1.46: Password used for registration.

[Analysis]
1. Storage structure of data
If we use character arrays to store passwords, there are two possible ways to assign initial val-
ues: the first is to assign characters one by one, while the other is to assign a string. Characters
stored in these two approaches are the same, but termination mark ‘\0’ will be automatically
inserted to the end of the string by the system, as shown in Figure 1.47.

Storage
solution 1 char password1[20]={'a','b','c','2','4','6','8','0'};
What is the
Storage difference between
solution 2 char password2[20]="abc 24680";
these two solutions?

Solution 1
Index 0 1 2 3 4 5 6 7 8 9 ... 18 19
Registered
password 'a' 'b' 'c' '2' '4' '6' '8' '0'

Solution 2
The string has
Index 0 1 2 3 4 5 6 7 8 9 ... 18 19
termination mark
Registered
password 'a' 'b' 'c' '2' '4' '6' '8' '0' \0

Figure 1.47: Storage approaches of character sequence.

Note: one can store strings of any length in C. When storing strings in character arrays, pro-
grammers need to make sure that the array size is large enough so that the longest string can
fit in; if the string is longer than the array, characters beyond the array bound will override data
after the array in memory.
2. Algorithm description
Figure 1.48 shows the stepwise refined algorithm.
38 1 Arrays

Top-level pseudo code First refinement


Compare keyboard input characters Store registered password in array password[ ]
and registered password characters Read keyboard input character in ch
one by one while there is remaining input
Output “Password is wrong" upon Compare ch with password[ ]
mismatch Output “Password is wrong” upon mismatch
Output “Password is correct” if there
Output “Password is correct” if there is no mismatch
is no mismatch

Second refinement
char password[20]; int i=0;
ch=getchar();
while (ch!='\n')
if (ch != password[i])
printf(“Password is wrong");
Jump out of loop
ch=getchar();
i++;
if ( i==strlen(password) )
printf(“Password is correct");

Figure 1.48: Password verification.

In the second refinement, ch! = ‘\n’ checks whether there are more inputs. The loop control
variable i acts as a counter as well. strlen is a library function that computes string length (not
counting termination mark ‘\0’). To determine whether the entire string has been checked, we
compare i with the string length.

3. Code implementation
01 #include <stdio.h>
02 #include <string.h>
03 int main(void )
04 {
05 int i=0;
06 char ch;
07 char password[20]="abc24680";
08 ch=getchar();
09 while (ch!='\n')
10 {
11 if (ch != password[i]) break;
12 ch=getchar();
13 i++;
14 }
15 if (i==strlen(password)) printf("Password is correct\n");
16 else printf("Password is wrong\n");
17 return 0;
18 }

Note that the header file for library function strlen on line 19 is included on line 2.
1.5 Operations on character arrays 39

Example 1.7 Cracking Caesar code


What did the mysterious email Daniel sent to his father (see Figure 1.49) say? How many charac-
ters were shifted? How should Mr. Brown implement his algorithm?

ciphertext[]="lettc fmvxlhec hehhc pszi csy"

Ciphertext Plaintext
Decryption

Left shift by ? positions

Figure 1.49: Cracking Caesar code.

[Analysis]
1. Data processing
Without loss of generality, we shall use right shift (the alphabet is shifted by one character to its
right each time) in the following discussion. To crack the ciphertext, we can list all 26 possible
results and look for a meaningful string. Figure 1.50 shows the case of shifting by one character.

We will use right


Ciphertext Plaintext shifts instead of left
Decryption
shifts for simpler
Right shift by x positions computation

Ciphertext Shift Plaintext


Normal case ciphertext[i] ciphertext[i]+1
Special case ‘z’ ‘a’ The range of shift
1 position
'z'+1='a'+25+1 of English letters is
Derivation ‘z'='a'+25
→'a'+26%26 0 to 25, so mod is 26

ciphertext [i]=(ciphertext [i]+1 -'a') %26 + 'a'

ciphertext+1 corresponds to the


Universal position of the character in the alphabet
formula

Figure 1.50: Character shifting analysis.

Normally, if ciphertext is ciphertext[i], its plaintext would be ciphertext[i] + 1, except character


‘z’, whose plaintext is ‘a’. In other words, we need to return to the beginning of the alphabet
when reaching the end. Let us examine this case more carefully.
Ciphertext character ‘z’ can be represented by the character ‘a’ plus 25, namely ‘z’ = ‘a’ + 25.
Hence plaintext ‘z’ + 1 = ‘a’ + 25 + 1 should be the character ‘a’.
We can use modular arithmetic (mod 26) to eliminate the 26 in the equation. Modular arith-
metic helps us return to the beginning of the alphabet when going out of bound.
By now, we have derived the universal formula for right shifting by 1 character. The expres-
sion inside parentheses indicates the position of ciphertext character plus 1 in the alphabet. For
example, if character ciphertext[i] is ‘b’, we have:
40 1 Arrays

ciphertext[i]+1-'a'='b'+1-'a'=2 //’b’+1 is shifted by 2 characters in the alphabet


(ciphertext[i]+1-'a')%26+'a'=2%26+'a'='c' //’b’ becomes ‘c’ after right shifting by 1
character

2. Algorithm description
Figure 1.51 shows the pseudo code of the algorithm.
In the second refinement, ‘\0’ is used to determine whether the entire string has been proc-
essed. Space is represented by a space wrapped with single quotation marks. The shifted ci-
phertext is computed using the formula we derived earlier. When printing strings, a number
indicating the number of characters shifted is added to the beginning. Finally, we need to find a
meaningful string in printed contents manually.

3. Code implementation
01 #include "stdio.h"
02 #define SIZE 80
03 int main(void)
04 {
05 char ciphertext[SIZE]="lettc fmvxlhec hehhc pszi csy";
06 int i=0,j=0;
07 printf( "%s\n",ciphertext);
08 while (j<26)
09 {

Top - level pseudo code First refinement


Repeat process below 26 times
– Right shift string by 1 position while not reaching string end
– Print string ciphertext is not space
– Repeat process above 26 times right shift ciphertext
print ciphertext string

Second refinement
while(j<26)
while(ciphertext[i]!='\0') //while not reaching string end
if (ciphertext[i] !=‘ ’) //skipspace
ciphertext[i]=(ciphertext[i]+1-‘a’)%26+‘a’ //right shift by 1
i++ Finally, we need
printf( "%d:%s\n", j, ciphertext ) to manually find
meaningful string
i=0
j++

Figure 1.51: Algorithm for cracking Caesar code.


Exploring the Variety of Random
Documents with Different Content
"Oh, unluckily we have some evangelical bishops."
"A bishop evangelical! don't you consider that a great wonder,
Sir?"
"I consider it a great calamity to our church."
"Exactly so; then I suppose we shall always be annoyed with
these evangelical clergy if the bishops sanction them. I hope you
won't turn evangelical."
"Not while I retain my reason. When that is gone, I may go off
too."
My readers who are but superficially acquainted with the religious
habits and style of conversation which prevail in the higher walks of
life, may be induced to imagine that I have given a strong colouring
to some parts of my narrative, but I assure them that I have not.
Indeed, had I quoted the epithets and the phrases which, I know,
are sometimes employed, when a certain class of fashionable
Christians, with their anti-evangelical pastors, venture to discuss
religious subjects, and animadvert on religious people, my pages
would be too disfigured to pass through the hands of the pious
reader.
It is to be lamented that many intelligent and amiable persons,
who occupy very prominent positions amongst us, and who are
admired and esteemed by all who know them, are as ignorant of the
nature and the design of Christianity as the ancient Scythian or the
modern barbarian. They imagine that they are Christians, because
they are born in a Christian country; that they are very good
Christians, because they sometimes go to church; and that they are
safe for another world, because their conscience does not condemn
them for the practices in which they now indulge themselves. And if
any one, in the most guarded way and the kindest tones of speech,
venture to suggest the possibility of self-deception, they are
offended, or take refuge in the belief that their hearts are too good
to be guilty of such a mean vice. They keep to the religion in which
they were born and educated; and this to them is the ark of safety.
Yes, you are a Christian in Britain, as you would be a Mahometan
if you had been born in Turkey; but search the Scriptures, and
examine if the design of Christianity has ever been accomplished in
you. Have you been born again? No. That subject you ridicule,
because you do not understand it. Have you had repentance towards
God, and faith in our Lord Jesus Christ? No; and if these subjects
were pressed upon your conscience with the affection of apostolic
compassion, and ardour of apostolic zeal, you would retire
displeased, if not disgusted, with the minister who dares to enforce
them as essential to your safety and happiness. Are you crucified to
the world by the moral influence of the death of Jesus Christ?
Crucified to the world! The very phrase, though scriptural, grates
offensively on your ear! Crucified to the world! O no. You are
devoted to its pleasures, its follies, its amusements. Shut up the
theatre, abolish cards, interdict the assembly and the ball, and how
would a large portion of our modern Christians be able to support
life?
You may imagine that you are a good Christian, because you
sometimes go to church; but an occasional visit to a material temple
will not produce that moral transformation of the soul which is
essential to fit you for the holy exercises and enjoyments of another
world. You may reject these questions which I now propose to you;
but before you reject them, permit me to urge you to search the
Scriptures, and then you will see that they have a paramount claim
on your attention. Can you be a Christian unless you possess the
spirit, and are in some degree conformed to the image of Jesus
Christ?
But it ought not to excite our astonishment, though it may our
tenderest sympathy, to see the great majority of those who move in
fashionable life passing away their time amidst the gaieties and
follies of the world, when they are sanctioned, if not encouraged by
the clergy, who ought to teach them better, both by precept and
example.
We have ministers of religion who do not hesitate to hold up to
ridicule and contempt the essential doctrines and self-denying
precepts of their own faith; and attempt, as far as the influence of
their example can extend, to banish all serious and devout piety
from the social circle. They see no harm in customs which the spirit
and even the letter of the Scriptures condemn; and sanction by their
presence those scenes of human folly and gaiety which have
captivated and ruined thousands, who were once the ornaments of
their fathers' house.
Such ministers not only sanction the customs of the world, but
they discountenance all serious piety, and declaim against their
evangelical brethren as disturbers of the peace of the church. If
Christianity be a cunningly devised fable—if the life of faith and of
practical devotedness of the soul to God be mere fancies—if heaven
and hell be the conceptions of romance, brought into the pulpit to
terrify the credulous and please the sanguine—I should not hesitate
to pronounce a heavy censure on those ministers who bring forward
these subjects so often, and who enforce attention to them with so
much ardent and impassioned eloquence.
But if Christianity be true—if the final happiness or misery of the
human soul depend on faith in Christ—if the glories of heaven and
the terrors of hell are realities which exceed the power of man to
describe—then even the most sceptical must admit that the
ministers of religion ought, with great boldness and impassioned
earnestness, to rouse their hearers to a serious and immediate
attention to these great, these awful subjects; and ought they not to
teach by example, as well as by precept? and by the purity of their
morals—by their religious habits and style of conversation—give
strong and unequivocal proofs that they preach what they believe,
and believe what they preach?
But let no Christian, whatever rank he may hold in social life, or
whatever degree of reputation he may have attained for intelligence,
or good sense, or for amiability of temper, presume to hope that he
will ever be able to make a scriptural profession of religion (after he
has felt the power of it) without exciting the displeasure, if not the
opposition, of his irreligious relatives and friends. They will not
object to the religion of forms and ceremonies; to the religion which
is confined to the temple, or to the bed of sickness; to the religion
which allows of a conformity to the gaieties and the follies of the
world, and which frowns from its presence all references to death, to
judgment, to heaven, and to hell; but the religion which consists in
the moral renovation of the soul, which identifies man with a living
Saviour, and which raises his anticipations to the glories of the
invisible world, they despise, and cast it from them as a strange
thing, and then ridicule it as contemptible.
THE DARK VALE ILLUMINED.
J ust as we were going out to take an evening walk, the
postman delivered a letter addressed to Mrs. Stevens;
she read it, and in silence handed it to her husband. I
apprehended, from the expression of her countenance
and her excited manner, that it conveyed some painful
intelligence; and this was immediately confirmed by Mr. Stevens,
who said, "This is a letter from our nephew, Mr. Lewellin, informing
us of the sudden and dangerous illness of his mother, and he
requests that we hasten to see her."
"The intelligence," said Mrs. Stevens, "is most painful, but it does
not greatly surprise me; I had something like a presentiment of it in
the mental visions of the past night; I saw her leaning on the top of
her staff, standing near the brink of a river, whose waters divided of
themselves, as a radiant brightness gilded the whole horizon; and
while listening for some moments to the sounds of sweetest
harmony, I awoke, and found it was a dream. Thus my senses were
locked up in the chambers of slumber, that my spirit might go and
commune with my dear sister before she leaves us."
A carriage was immediately sent for, and we set off from
Fairmount about eight o'clock. It was a cloudy moonlight night. We
rolled on in silence, being too much absorbed in painful thought and
expectation to break the quiet which grief requires for the solace of
her own feelings. At length Mr. Stevens, alluding to Mrs. Lewellin's
illness, said, "With what different emotions do the inhabitants of the
visible and invisible world contemplate the same event! While we are
anticipating her departure with deep sorrow, the glorified spirits of
her deceased husband, and child, and father, are attuning their
harps of joy, to celebrate her entrance among them."
"Very true," Mrs. Stevens replied; "our loss is their gain; but it is
as natural for us to deplore our loss, as it is natural for them to exult
in their gain."
"I admit, my dear, that we cannot, while encompassed by human
infirmities, avoid feeling the pang of sorrow on such an occasion as
this, though we may moderate its intensity by reflecting on our own
dissolution, which will introduce us into the society of those who
obtain the prize of immortality before us."
We had no difficulty in procuring a change of horses at each
succeeding stage; nothing worthy of remark occurred during the
journey, and on the following morning we arrived at Mrs. Lewellin's
cottage.[11] The same jessamine, and honey-suckles, and rose trees
adorned its tasteful front; the same hawthorn hedge inclosed its
well-cultivated garden; the little wicket-gate still swung on its hinges,
as when I paid my first visit six years before; but they had lost their
attractions, or I had lost my power of enjoyment.
On seeing Mr. Lewellin, Mrs. Stevens said, "Is your mother still
living, my dear George, or has she left us?"
"O no, aunt, she has not left us; she has made many inquiries
about you, and longs to see you. She says that when she has seen
you she shall depart in peace."
"When was she first taken ill, and what is the nature of her
disorder?"
"She has not been well for some weeks, but her indisposition
created no alarm. On Sabbath morning she felt better, and went to
chapel, where she commemorated the death of the Redeemer, with
her Christian brethren. As she was returning home she was exposed
to a heavy shower, and though she took every precaution to prevent
any evil consequences, yet, early in the evening, an inflammation of
the bowels came on, which has raged with unabating violence; and
her medical attendant says that he does not expect that she can live
through the day. Her pains have been excruciating, but she has
borne them with the fortitude and resignation of a Christian, and
now she seems to be enjoying that fatal ease which is the
immediate forerunner of dissolution."
On entering her room she received us with composure, and calmly
said to her sister, "Weep not for me, the days of my widowed
mourning are drawing to a close. I have long lived secluded from the
world, and I can leave it without a sigh."
"Then," I said, "you have no fear?"
"Fear! why should I fear? I know I am in the valley, but it is
illumined with the light of life. I have often dreaded this hour, yet it
is the happiest hour I have ever known."
"To us, my dear sister, it is a most painful hour."
On seeing her sister and her son in tears, she said, "I hope you
will compose yourselves, that we may enjoy each other's society on
this side Jordan, which I am soon to pass.... My dear George,
receive once more, and for the last time, the congratulations of your
mother on the honour which the God of all grace has conferred on
you, in adopting you as his son. I now solemnly charge you, before
Him and the pious friends now with you, always to act worthy of
your high vocation. Maintain the dignity of your Christian character
by the integrity of your principles, your decision, and your zeal for
the honour of the Lord of life and glory. As much of your future
happiness and respectability will depend on the choice which you
may make when you settle in life, let me beseech you to marry only
in the Lord—prefer piety to beauty, good sense to a large fortune,
and remember that a meek and quiet spirit is the most beautiful
ornament in the home of a righteous man."
She then turned towards Mr. and Mrs. Stevens, and said, "I thank
you for all your kindness to me and mine in the days of our
adversity. The Lord reward you a thousand fold. I have only one
legacy to leave, and I leave it to you. I bequeath to you my dear
boy; take care of him for my sake."
The pious rector of the parish made an early call. Mrs. Lewellin
received him with a sweet smile, and motioned him to be seated.
After inquiring for her welfare, he thus accosted her: "What would
you now do without a Saviour?"
"I should perish! But I have a Saviour whose blood cleanseth from
all sin."
"His blood," he said, "is of more value than a thousand worlds."
She replied, "It is inestimable! It is inestimable!"
We all knelt down, and this man of God devoutly prayed that she
might have "an entrance ministered unto her abundantly into the
everlasting kingdom of our Lord and Saviour Jesus Christ."
As the cottage was not large enough for our accommodation, the
pious rector invited us to his hospitable home, but Mrs. Stevens
resolved not to leave her sister. There was grief over the whole
village as the rumour spread that she was dying. Her benevolence
had added lustre to her piety, and such was the veneration and
attachment in which her character was held, that many a hand
knocked softly at the door of her cottage, and many a low voice
inquired how God was dealing with her. About noon she fell into a
sweet sleep, and slept for several hours; she awoke refreshed,
animated; a heavenly serenity beamed on her countenance, as she
exclaimed, "Oh! the bliss of dying!"
"You are happy, mother, in the prospect of death."
"Happy, my child, yes, my joy is unspeakable."
Her voice suddenly faltered, yet she gently whispered "Farewell"
as her son caught her in his arms, and with her eyes fixed on him,
after one strong convulsive struggle, she expired.
Mrs. Lewellin had generally attended the village church in the
morning of the Sabbath, and in the evening she usually heard an
excellent minister of Christ who preached in a Dissenting chapel, and
when reproached for her liberality by the more bigoted, she used to
say, "I have no objection to go where I can hold communion with
the Saviour." Adjoining the chapel there was a burying-ground, to
which she had long been accustomed to resort, as favourable to
meditation, and on returning from an evening walk with the pious
rector, we passed near it, and were induced to visit the spot which
she had selected as the place of her burial; it was overshadowed by
a large oak tree, and partially inclosed with some evergreens, which
she had transplanted from her own garden.

THE DARK VALE ILLUMINED.


Vol. i. page 300.

"You see," he said, "how instinctively we love immortality, and as


we cannot live here always, we wish life to flourish over the tomb in
which our body is decaying. This is simple and beautiful. She was a
woman of great taste, and a Christian of high principle. Her
knowledge of the gospel was clear, comprehensive, and profound;
and she displayed, during her residence with us, a spirit as free from
the ordinary imperfections of the human character as I have ever
beheld."
I told him that I had been requested to ask if he would attend her
funeral.
He replied, "Certainly, if the family wish it. I respected her—I loved
her. I often retired from the labour and perplexity of study to pass
an hour with her, and always found her conversation of such a
spiritual, catholic, and heavenly cast, that I never failed to derive
great benefit from it. Her conversation was remarkably suggestive;
she has helped me to many texts, and some of my most useful
sermons owe their origin to her observations and reflections. I was
always delighted when I saw her in church, because I knew she was
praying in spirit for the success of my ministry."
Upon the day appointed for her burial almost every inhabitant of
the village attended, to pay the tribute of respect to her memory.
The corpse was taken into the chapel, and after the minister had
read the 15th chapter of 1st Corinthians, and delivered a very simple
impressive address, and offered up a solemn prayer to "the God of
the spirits of all flesh," it was interred amidst the sighs and tears of a
large concourse of spectators. Some were attired in full mourning,
many were in half mourning, but the majority had merely put on
their Sabbath dress, being too poor to purchase clothes for the
occasion. There was one female of the group, about the age of
thirty, with an infant in her arms, whose appearance and manners
indicated the most poignant grief. During the time the minister was
conducting the service, the tear fell silently on her cheek, but when
the body was lowered into the grave she wept no more, but
appeared convulsed, and then advanced to the brink of the grave,
and after looking with intense eagerness for some seconds, she
exclaimed, "Lover and friend hast thou taken from me," and fell
senseless on the ground. On inquiry, I found that she was the widow
of a poor woodman, who was killed by the falling of a tree, and who
was left with three children, and had another born three months
after his father's decease. She lived about a quarter of a mile from
the cottage, and as Mrs. Lewellin used to pass by her residence
when taking her morning walks, she often called to see her. On one
occasion (the poor woman told me the next day), after giving her
weekly donation, she gave her a tract, and requested her to read it.
"I did read it," said the weeping widow, "but I could not understand
it. When she called the next time she asked me if I had read it, and
when I told her I could not understand it, she said, 'Read it again,
but before you read it the second time, pray to God for wisdom to
enable you to understand it. He can give it, and he will give it if you
ask him.' I did so. The Lord has answered my prayer, and made me,
I trust, wise unto salvation. But he has taken from me my guide, my
counsellor, and my friend. The death of my husband, which threw
me on the charity of the parish, and deprived my dear babes of a
father, was a great trial, but it did not pierce my heart like this. I
sometimes think my heart will break, then I go and pray to the Lord
for submission to his holy will, and I find myself better; but it will be
a long time indeed before I shall be able to get over it."
I mentioned this incident at the rectory, and then learned that the
poor widow was a regular attendant at the church, and was
considered decidedly pious. Mrs. Stevens, having ascertained the
amount of her departed sister's weekly donation, engaged the rector
to become her almoner, and the usual payment was continued. Mr.
Lewellin was so affected by this testimony to the memory of his
mother, that he increased the sum; and before he left Stanmoor he
called to see the bereaved sufferer, and gave her several articles of
furniture, which once adorned the lonely cottage of her whose
remains we had committed to the tomb.
The evening before our departure, I retraced the steps I had
trodden on my former visit to this village; and fixing on the same
hour for my ramble into the vale, I anticipated another interview
with the pious shepherd. As I walked on I heard the bleating of the
sheep, and saw them at a distance ascending the steep path which
led up to their fold in a neighbouring field. I heard also the barking
of the dog; and soon afterwards the shepherd made his appearance,
but I knew him not.
"Is the old man dead," I asked, "who kept his flock here about six
years ago?"
"Yes, Sir; he died about Christmas."
"Did you know him?"
"He was my father; and a better father never lived."
"He was a religious man; was he not?"
"Yes, Sir; and he died in the faith of Christ."
"I hope you are following in his steps."
"It is, Sir, my wish and my prayer to be a follower of them who
through faith and patience inherit the promises."

On the Sabbath morning after our return to Fairmount, the Rev.


Mr. Ingleby preached from Acts xxi. 16, "An old disciple." We were
much pleased with his sermon, particularly with the following
passage: "When we see an old disciple moving amidst the activities
and amenities of life, we see a living monument of the faithfulness
and loving-kindness of God; and when we follow him to his grave,
though we may sorrow over his departure from amongst us, yet our
sorrow is not to be without hope; he still lives, and lives in a new
form, amidst new scenes of beauty and of grandeur, and with new
associates; he is with Christ, assimilated to his likeness, beholding
his glory, and enjoying sweetest intercourse with him. His gain by his
death, should reconcile us to our loss."
"The loss of my dear sister," said Mrs. Stevens, "is the most
afflictive trial I have ever been called to endure. Memory carries me
back to the days of childhood, to the riper years of age, and to the
associations with which my dear departed sister is inseparably
entwined. But the pleasing charm soon vanishes, for she is gone."
"But, my dear," replied Mr. Stevens, "though this affliction be
grievous, yet you might have been visited by one much more
severe."
"Yes, I know it. I might have lost you. That would have been a
more overwhelming one. I wish to be resigned—it is my constant
prayer—and I hope that I do not cherish any murmuring disposition,
but I cannot help feeling; yet I fear lest I should indulge my
mourning to an excess."
"Excess of grief, my dear, is to be guarded against, as it unhinges
the mind, induces a melancholy cast of temper, and dispossesses
comforts which are still preserved, of their power to interest and
delight. Mourn you may, but you must not mourn as one 'who has
no hope.' For hope, even the sweetest hope that can lodge in the
human heart, is yours. Death has merely separated you for a
season, he has not destroyed your union. You now live apart, but no
impassable gulf lies between you—only a narrow grave. Let your
mourning, therefore, be moderate and submissive."
"Yes," Mrs. Stevens replied, as her countenance began to assume
its former cheerfulness, which had vanished from the moment the
first intelligence of her sister's illness was received, "my sister lives—
she lives a purer and a happier life than I ever expect to live, till I
cease to breathe this vital air—she now sees the King in his beauty—
she now unites with all the redeemed in singing, 'Unto him that
loved us, and washed us from our sins in his own blood.' She is, and
ever will be with the Lord. These words comfort me."
"Then let me hear the words which comfort you," said Mr.
Lewellin, who caught this latter sentence as he entered the parlour,
"as they may serve to comfort me. My heart never throbbed as it
has done since I lost my mother—a loss I have been anticipating for
years, but I now find that it is more desolating than I ever
anticipated."
"It is an event," said Mr. Stevens, "which has brought along with it
many alleviating circumstances. She died in peace. No dubious
uncertainty distracted her, no dread forebodings appalled her, no
torturing anxieties for those she loved agitated her breast. Hers was
an enviable death."
"Yes," said Mr. Lewellin, "her sun did not go down till the evening;
and even then it was light. She told me that for several days before
her last illness she suffered great mental perplexity and horror, that
she not only doubted her personal piety, but the truth of revelation.
She was driven almost to a state of despair; and on the Sabbath
morning, when she left her cottage for the house of prayer, she
resolved not to receive the memorials of the Saviour's death. The
text from which the Rev. Mr. Bates preached, was taken from Judges
viii. 4, 'Faint, yet pursuing.' There was one paragraph in the sermon
which gave her sweet relief. It was to this effect: 'The most favoured
servants of the Lord are liable to momentary seasons of suspicion
and depression; and some have been left for days, and some for
months, not only without consolation, but even without hope. But
shall we say that as soon as they lose their enjoyments they make a
shipwreck of their faith? Shall we say that the design of God—the
practical efficacy of the atonement—the continual indwelling of the
Holy Spirit—depend on the ever fluctuating and ever varying
temperament and feelings of the mind, which is sometimes so
perplexed and distracted by unknown causes, as to be incapable of
believing its own faith, or deriving felicity from its own sources of
blessedness? Oh! no. There are periods in the mysterious life of an
heir of salvation when he is left without comfort, if not without hope,
and then comes on the hour and the power of darkness; but this
singular dispensation does not disinherit him, or leave him an
orphan, in a state of privation and abandonment; neither does it
destroy the vitality of his religious principles, but it is intended to let
him feel a portion of that misery which he deserves, but from which
he is delivered through the blood of the Lamb.'"
"Had my sister left us under this mental gloom, I should have had
no doubt," said Mrs. Stevens, "of her present happiness; but it
would have been an additional cause of grief."
"Sometimes," I observed, "it pleases God to leave his most
eminent servants without any strong consolation in their last hours;
and sometimes he elevates them to a participation of the felicity of
heaven, before he permits them to enter. Hence there is no
undeviating uniformity in his procedure; but yet he keeps our
practical good in view by all the dispensations of his will. When I see
a holy man overwhelmed with sorrow on the eve of his departure, I
am convinced there is no absolute, no meritorious connection
between an exemplary life and a triumphant death. This conviction,
coming through such a medium, destroys all self-complacency, and
impels me to place all my dependence for salvation on Jesus Christ.
But when I see a sinner of like passions and infirmities with myself—
one who has wept over defects and transgressions similar to my own
—rising above fear, eagerly and yet submissively anticipating his own
dissolution, giving utterance to thoughts and feelings more nearly
allied to the glory and purity of the heavenly state than to the dark
obscurity of the present, I feel a degree of gratitude to the Saviour
for making manifest life and immortality, which, for its full
expression, I must wait till I see him as he is, and am made like unto
him."
"The death of our friends," said Mr. Stevens, "is always an
afflictive event, but it is sometimes a salutary one. It reminds us of
our mortality, and brings before our imagination the unseen realities
of an eternal world. It teaches us what shadows we are, and what
shadows we are pursuing:—

'Our dying friends come o'er us like a cloud,


To damp our brainless ardours; and abate
That glare of life, which often blinds the wise.
Our dying friends are pioneers, to smooth
Our rugged pass to death; to break those bars
Of terror and abhorrence nature throws
'Cross our obstructed way; and thus to make
Welcome, as safe, our port from ev'ry storm.'"

"To repine," I observed, "under any of the dispensations of


Providence, would be to display a temper which no Christian should
cherish; but to repine at the grave of a pious friend, discovers not
only a spirit of hostility to the Divine will, but an unsubdued
selfishness, which would deprive another of happiness, merely to
augment our own."
"Resignation is our duty, and this brings with it its own reward; yet
it is a disposition which does not spring up spontaneously in the
heart. It is one of those good gifts which cometh from above; but,
like every other disposition which claims the same origin, it must be
exercised before it can become perfect; and when perfected, or
when approaching near perfection, it can rejoice in tribulations also."
INTEMPERATE ZEAL.
The Rev. Mr. Roscoe and his lady, who had not been at the
mansion for several years, now intimated their intention
to pay a visit to their brother. He was the youngest son
of the family, and at an early age had decided for the
church, as a profession more easy, if not so lucrative as
some others. Having finished his career at Oxford, where he was
more distinguished for his love of pleasure than regard for
academical honours, he obtained ordination, and settled in a parish
in Somersetshire. For nearly fifteen years he remained unmarried,
devoting himself to a life of pleasure, and paying but little attention
to the claims of his parishioners. The dignity of the priest was
lowered by the imperfections of the man, and the church was
forsaken for the village chapel. At length he was, by the
remonstrances of his friends, induced to pursue a course more
becoming the sanctity of his office; he withdrew from his former
companions, abandoned the sports of the field and of the gaming
table, and turned the torrent of his displeasure against those who
had separated themselves from the church, on account of his former
irregularities. He had reached the age of forty when he married the
eldest daughter of a neighbouring magistrate, a lady distinguished
by superior intelligence, and a most catholic spirit. They had two
children, who both died in infancy. So deeply wounded was the heart
of the mother by these bereavements, that she long abandoned
herself to the agonies of grief; and though time had now removed
its poignancy, yet she often alluded to her babes and their early
death, in a tone and manner which proved that they still lived in her
fond remembrance.
Their arrival at their brother's mansion had been expected for
several days, and every preparation was made to render their visit
pleasant and profitable. At length they came; and though the Rev.
Mr. Roscoe was a reformed man, yet he discovered no signs of being
a spiritual one. He was become more moral in his habits, but less
tolerant in spirit; and soon convinced his brother and his niece that
"the things which are seen and temporal" had a more powerful
ascendency over him than those "which are unseen and eternal." He
declined the invitation of the Rev. Mr. Cole, to preach on the
following Sabbath, as he was too much fatigued by his journey to do
duty; but consented to accompany the family to church. It was a
beautiful morning, still and serene; no sound was heard but the
melody of the birds, and the "church-going bell." Mr. Cole read the
Liturgy in his usual heavy, monotonous tone, which was no less
offensive to the ear, than a certain air of carelessness which hung
over his manner was repulsive of devotional feeling. He announced
his text in an elevated pitch of voice, which immediately arrested the
attention of his congregation. "The subject," he remarked, "which I
shall submit to you this morning, is taken from the tenth chapter of
St. Paul the apostle's Epistle to the Romans, and the second verse:
—'For I bear them record that they have a zeal of God, but not
according to knowledge.'"
He began by declaiming against the spirit and the conduct of the
ancient Pharisees, who were, he asserted, the troublers of the
church in a former age; and then expressed his deep regret that the
sect was not yet become extinct, but was even at this moment
augmenting its numbers, and threatening, by its untempered zeal,
and its invincible ignorance, to tarnish the lustre and destroy the
foundation of the church which is fostering them in her bosom. "If,"
said he, "we run a comparison between the modern Calvinists, who
unhappily stand connected with our venerable Establishment—the
admiration and envy of the world—and the ancient Pharisees, we
shall find that they bear a close resemblance to each other; and
though a good man will pause before he gathers on his lips the
denunciations of inspired writ, yet a high sense of duty compels me
to say that the woes which our Saviour uttered against the latter,
stand directly pointed against the former. The ancient Pharisees set
aside the weightier matters of the law to attend to the ceremonials
of religion; they prescribed no bounds to their proselyting spirit, for
they would encompass sea and land to gain even one proselyte; and
when they had gained him, our Saviour says that they made him
twofold more a child of hell than themselves, though they made
bolder and higher pretensions to religion than any other sect. And
who, when looking at this picture of the ancient Pharisees, does not
recognize the portrait of our modern Calvinists?—'For I bear them
record that they have a zeal of God, but not according to
knowledge.' But the modern Calvinists conduct themselves with less
reverence for the authority of our church, than the Pharisees
discovered for the authority of theirs; for they will dare to reject
some of our established doctrines, and explain away the import of
some of our long-settled rites and sacraments."
He then went on to prove, by quotations from the fathers and the
Book of Common Prayer, that baptismal regeneration is the only
regeneration which is necessary or possible; and positively asserted
that the conversion of persons who are already members of the
apostolic Church of England, is a mere fiction of modern fanaticism.
"These Calvinistic clergy," he added, "declaim against good works,
and exalt a dogmatic belief in certain crude opinions, as the only
necessary condition on which sinners can obtain the forgiveness of
Almighty God." Then he attempted to prove that the people must
necessarily become corrupt, among whom salvation is proclaimed,
without requiring, on their part, good works as the essential
condition of its bestowment.
"Look, my hearers," he exclaimed, "on the destructive tendency of
their style of preaching. As soon as the officiating priest opens his
lips and gives utterance to his sentiments, there is an instantaneous
commotion in his congregation. Those who lived in peace are split
into divisions, and the family or the village which held the unity of
the faith, as propounded by our pure apostolic church, suddenly
becomes the arena of religious disputations and wrangling, and the
temple of peace and unity becomes a Babel of confusion and
discord.
"Indeed, in some instances, children will rise up in rebellion
against the authority of their parents, till the parents, wearied by
their obstinacy, or subdued by their importunity, imbibe the same
fatal opinions, that they may regain their domestic peace.
"These priests are zealous, and they pretend that they have a zeal
of God; but it is the fire and the smoke, whose effect is to darken
and to desolate, rather than that clear and radiant light which warms
while it illumines, and gives a verdant bloom to every springing
blade and opening bud, while it directs the passenger onwards on
his journey. In a word, the labours of these men, wherever they are
successful (and such is the fatality attending them that they are
always successful), tend to give a retrograde movement to our social
habits and enjoyments, and to carry us back to the gloomy times of
the Commonwealth, when the Puritanical devotee was seen weeping
between the porch and the altar, but never indulging himself in the
innocent recreations of life.
"In fine, I feel myself compelled once more to warn you against
their doctrines, as contrary to the doctrines of our incomparable
prayer-book; to warn you against associating with them, or hearing
them preach, as you may be entangled by their sophistry before you
are aware, and while you will deplore, in common with myself and
others, their existence within the pale of our pure apostolic church,
you will endeavour, by your influence and your example, to check
the progress of the moral contagion which they have introduced
among us. That the common people, who know not the Scriptures,
and who despise the authority of their authorized teachers, should
embrace the Calvinistic doctrines, is not surprising, because they
give them a complete indemnity against every species of crime, but
that any of the well-educated and intelligent members of society—
any who have not sacrificed their virtue nor lost their taste—should
feel a predilection for them, is one of those moral mysteries which
can be accounted for only from one of two causes—a partial
derangement of intellect, or the magic charm of enthusiasm.
"To conclude: Are they zealous in propagating their doctrines? be
you zealous in opposing them; are they zealous in gaining
proselytes? be you zealous in reclaiming them; are they zealous in
putting an end to all the innocent enjoyments of social life? do you
display a superior degree of zeal in preventing such a fatal evil, that
we may enjoy life as we have been accustomed to enjoy it in our
social circles, and thus prove to a sceptical and a fanatical age, that
we can be religious without being melancholy or morose, and fit
ourselves for the happiness of a future world without sacrificing the
pleasures of the present."
When the service was concluded, the Roscoes walked home
together, but no one made any reference to the sermon, as all felt
convinced that it was directed against Mr. Roscoe, who appeared,
during the whole of the afternoon, unusually reserved. This reserve
was regarded by some of the family as a decisive evidence that the
sermon had produced its intended effect; and the polite and friendly
manner in which he received the Rev. Mr. Cole, who called in the
evening, seemed to confirm this opinion. Next morning, as they sat
at breakfast, the Rev. Mr. Roscoe said that he had anticipated great
pleasure from his visit, but, he added, "I certainly did not anticipate
the feast of delight which I enjoyed yesterday. Mr. Cole surpassed
himself. I think he gave us a correct portraiture of modern Calvinism.
O, it is a gloomy system of religion! just suited for fanatics or
enthusiasts. Don't you think Mr. Cole a very clever and a very
intelligent man?"
"Yes," replied Mr. Roscoe, "I think him clever and intelligent, and a
man of rather extensive reading. We have often passed many
pleasant evenings together in discussing literary and scientific
questions, and I have uniformly admired his dexterity in reasoning,
and the aptness of his illustrations; but, in my opinion, something
more than learning and intelligence is necessary to enable a person
to understand the scheme of salvation which is contained in the
Scriptures."
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like