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

Programming In C Volume 2 Composite Data Structures And Modularization instant 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, functions, and modularization in C programming. The document also provides bibliographic information and links to related resources and other programming books.

Uploaded by

olivamenner
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)
11 views

Programming In C Volume 2 Composite Data Structures And Modularization instant 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, functions, and modularization in C programming. The document also provides bibliographic information and links to related resources and other programming books.

Uploaded by

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

Programming In C Volume 2 Composite Data

Structures And Modularization download

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

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


Zhou

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

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.


Random documents with unrelated
content Scribd suggests to you:
bark, marked with grey spots, and leaves about three inches
long and two broad, oval, pointed, and serrated.

As a timber-tree the hornbeam is more esteemed on the Continent


than in this country. It grows readily in stiff soils, particularly on the
sides of hills; and is easily transplanted. The wood, which is white,
hard, and tough, is used by turners; and is wrought into cogs for
mill-wheels, screw-presses, the heads of beetles, handles of working
tools, and other instruments and machinery in which great strength
is required. As fuel it is preferred, on account of its readier
inflammability, to most other kinds of wood. The inner bark is used,
in some countries, for dyeing yellow.

From the foliage of the hornbeam being luxuriant, and admitting of


being clipped, without injury, into any of those forms which the old
French garden style required, this tree was formerly much more
planted in England than it is at present. It preserves a great portion
of its withered leaves through the winter; and, if properly planted as
a hedge, it forms an excellent fence. The German husbandman,
when he erects a fence of hornbeam, throws up a parapet of earth,
with a ditch on each side, and plants his sets (which he raises from
layers) in such a manner that every two plants may be brought to
intersect each other, in the form of a St. Andrew's cross. In that part
where the plants cross, he scrapes off the bark, and bends them
closely together with straw. In consequence of this operation the
two plants consolidate into a sort of indissoluble knot, and push,
from the place of junction, horizontal slanting shoots, which form a
living palisado or chevaux de frise; so that such a protection may be
called a rural fortification. These hedges, being annually and
carefully pruned, will, in a few years, become impenetrable in every
part. It is not uncommon in Germany, to see the high roads thus
guarded for many miles together; and great advantage might be
derived from adopting the same plan in many parts of our own
kingdom.
243. The PLANE-TREE (Platanus orientalis, Fig. 71) is
distinguished by having broad leaves, each with about five
principal divisions, and these subdivided into smaller ones.

By the ancient Greeks and Romans the plane-tree was highly valued,
on account of its grateful shade; and the latter were much delighted
by training it in such manner as to admit of their sitting beneath its
branches. Wherever they built their magnificent colleges for the
exercise of youth, in the gymnastic arts, as riding, wrestling,
running, leaping, throwing the discus, &c. and where also the
gravest philosophers met to converse together and improve their
studies, they planted avenues and walks of plane trees for
refreshment and shade.

Though now frequently planted in parks and pleasure grounds, the


sycamore (122) is, in many instances, preferred to it. The plane,
though a native of Asia and the southern parts of Europe, is very
hardy, grows rapidly, and will flourish in any common soil, and in any
aspect.

Its wood, at a certain age, becomes much veined; and,


consequently, is valuable for many kinds of domestic furniture, but
particularly for tables.

244. The CABBAGE-TREE (Areca oleracea) is an American


species of palm, which grows to the height of a hundred feet
and upwards, and is destitute of leaves until within a few feet of
the summit. The leaves, sometimes near twenty feet long, are
winged, and the leaflets are entire.

Such is the general elegance of this tree that it is frequently


denominated the queen of woods. Its fruit, which grows in bunches
from the top, is an oblong and obtuse kind of berry, of bluish purple
colour, and about the size of an olive. The sheaths of the flowers,
and the floral leaves, when first developed, are folded round each
other, enclosed in a thin, green, and spongy bark, eight or nine
inches in circumference, and constitute the part which is
denominated the cabbage. This is white, and, when boiled, is
esteemed a great luxury. It is also eaten raw as a salad, and fried
with butter; and its taste is said to resemble that of an artichoke.
This part is likewise frequently made into a pickle with vinegar and
spices.

We are informed that the cabbage-tree was first introduced into


Jamaica by Admiral Knowles, when governor of that island; and that
it has since been cultivated there with great attention. But it is
chiefly planted for its beauty, being considered too valuable to be
often cut down for the small portion of food which it thus affords,
however delicious that may be.

In the leaves of this tree there is a thread-like substance, which is


sometimes spun, like hemp, and made into different kinds of
cordage. The sockets or grooves formed by the broad part of the
footstalks of the leaves are used by the negroes as cradles for their
children; and on the inner sides of the very young footstalks there
are tender pellicles, which, when dried, may be converted into paper.
The trunks, when cleared of the pith, serve as water pipes and
gutters. Of the pith a kind of sago is made; and in this pith, after the
trees are felled, there is bred a large species of caterpillar which the
inhabitants of some of the West Indian islands eat as a great
delicacy.

245. The CATECHU, ARECA, or BETEL-NUT-TREE (Areca


catechu), is a species of palm which grows in the East Indies.

It is generally from thirty to forty feet high, and its trunk is six or
eight inches in diameter. The leaves, which grow on the summit,
are winged, having the leaflets folded back; and the fruit is a
pulpy berry with thin skin, containing a nut about an inch in
length, and of a rounded conical form.

The kernel of the areca-nut, which is covered by a thin, smooth, and


yellowish shell, is somewhat like a nutmeg, but contains, in the
centre, a white, soft, greyish, and almost liquid substance, which
becomes hard as the nut ripens. This fruit is in general use by the
Indians, who cut it into slices, mix it with other substances, wrap it
in the leaves of betel (22), and chew it much in the same manner as
the common people of our country chew tobacco. The consumption
of these nuts in India is almost beyond calculation. They are an
article of considerable trade, from port to port; and also from India
to China, but they are seldom brought into England, though they
might be of use in some of our manufactures.

The drug called catechu, and formerly terra japonica, was supposed
to be an extract prepared from the above nuts; but it is now
ascertained to be made from the wood of a species of mimosa.

MONADELPHIA.

246. The SCOTS FIR (Pinus sylvestris), which has its name from
growing wild in different parts of Scotland, is known from other
trees of the same tribe by having its slender and somewhat
needle-shaped leaves in pairs; its cones or seed-vessels
somewhat egg-shaped, mostly in pairs, as long as the leaves,
and the scales blunt.

This useful tree flourishes with greatest luxuriance on the north and
north-east sides of hills, in a poor and sandy soil, especially where
this is mixed with loam. If planted among rocks, or in bogs, it
seldom attains a large size; in black soil it becomes diseased; and in
chalky land it frequently pines away and dies.
Its timber, under the name of deal, is employed as the wood-work of
houses; for rafters, flooring, doors, the frames of windows, tables,
boxes, and other purposes, infinitely too various to be enumerated.
Frigates, and other ships of large size, have sometimes been
constructed of deal but these are by no means so durable as vessels
that are built of oak. Much of the deal which we use is imported
from Norway, and other northern parts of Europe. That from
Christiana, which is called yellow deal, or red deal, is frequently
brought over in planks, but more commonly in boards, each about
ten inches and half in width. The wood of such trees as are raised in
England is equal to the foreign wood in weight and durability, but its
grain is generally coarser.

The outer bark of the fir-tree may be used in the tanning of leather;
and it is said that, in the northern parts of Europe, the soft, white,
and fibrous inner bark is, in times of scarcity, made into a kind of
bread. For this purpose it is dried over a fire, reduced to powder,
kneaded with water, and a small portion of corn-flour, into cakes,
and baked in an oven. Children in Norway are very fond of the fresh
bark, in the spring of the year, either shaved off with a knife, or
grated with a rasp.

Common Turpentine is the resinous juice chiefly of the Scots fir,


obtained by boring holes into the trunks of the trees, early in spring,
and placing vessels beneath for its reception. It is of brown colour;
and has a strong odour, and disagreeable taste. In the distillation of
turpentine an essential oil is produced, called oil of turpentine, which
is extremely pungent. When the distillation is continued to dryness,
the substance which remains is known by the name of common
resin or rosin; but, if water be mixed with it, while yet fluid, and
incorporated by violent agitation, a substance is formed called yellow
resin.
Common turpentine is mostly employed as an ingredient in the
plasters used by farriers. The oil is occasionally used in medicine;
and, lately, it has been considered efficacious in cases of worms. It is
much employed by painters for rendering their colours more fluid; as
well as in the composition of different kinds of varnish used in floor-
cloth, umbrella, and other manufactures. The noxious spirit called
gin was formerly flavoured with juniper berries; but as these are
now too expensive, oil of turpentine, the taste of which in a slight
degree resembles that of juniper, is applied to the same purpose;
and considerable quantities of turpentine are thus consumed. The
common resin is used in plasters, for which its great adhesiveness
renders it peculiarly applicable. It is also of considerable importance
in the arts; and musicians rub the bows and strings of violins with it,
to take off the greasy particles which are there collected, as well as
to counteract the effects of moisture. Yellow resin is used in plasters,
and for other purposes in medicine.

Tar is obtained from the roots and refuse parts of the fir-tree, by
cutting them into billets, piling these, in a proper manner, in pits or
ovens formed for the purpose, covering them partly over, and setting
them on fire. During the burning, a black and thick matter, which is
the tar, falls to the bottom, and is conducted thence into vessels
which are placed to receive it, and from which it is afterwards
poured into barrels for sale.

Tar is an article of great utility in manufactures, and for various


economical purposes. It is much employed for smearing the rigging,
and other external parts of ships, to prevent their receiving injury
from moisture. It has been used in medicine both internally and
externally; and particularly tar-water, or water impregnated with tar,
was, some years ago, a popular remedy in various disorders, but its
virtues have been too much extolled. Although considerable
quantities of tar are prepared in this country, these are insufficient to
supply the demand; consequently we, every year, import great
quantities of it from Russia, Sweden, America, and other countries.
Pitch is usually made by melting together coarse hard resin and an
equal quantity of tar; or, as some writers state, by boiling tar with a
certain portion of water, until it becomes so thick that, on cooling, it
forms a hard black mass.

By the ancients pitch was much employed for giving flavour and
fragrance to their wines. With us it is of extensive use to mechanics,
and in numerous manufactures; but the principal demand for it is in
ship-building, to secure the joints and crevices of the planks and
timbers, and for other purposes. When mixed with a certain quantity
of oil and suet, it is made into shoe-makers' wax; and, in conjunction
with whale fat, forms carriage-grease, or the substance with which
the wheels of carriages are smeared. The best pitch is imported
from Sweden and Norway: and, is of a glossy black colour, perfectly
dry, and very brittle.

Lamp-black is a soot formed by burning the dregs and coarser parts


of tar in furnaces constructed for that purpose. The smoke is
conveyed through tubes into boxes, each covered with linen, in the
form of a cone. Upon this linen the soot is deposited: and it is, from
time to time, beaten off into the boxes, and afterwards packed in
barrels for sale. This substance is employed in printing and dyeing;
and has its name from the practice that was formerly adopted of
making it by means of lamps.

247. The WEYMOUTH PINE is chiefly distinguished by its leaves


growing in fives, and its cones being smooth, cylindrical, and
longer than the leaves.

This species of fir-tree grows wild in North America, and succeeds


well in strong land in England. Its timber is white, of more open
grain than Scots fir, and not so heavy as that. In America it is
principally used for the masts of ships, for which, by its toughness, it
is peculiarly calculated.
248. The SPRUCE FIR (Pinus abies), a native of Norway, and
other Northern parts of Europe, is known by its short, and four-
sided leaves growing singly, and surrounding the branches; its
cones being cylindrical, the scales somewhat square, flattened,
and notched at the top

The wood of the spruce fir is what the English carpenters usually
denominate white deal. It is considered next in value to that
obtained from the Scots fir; and is remarkable for having few knots.
On account of its lightness it is peculiarly adapted for packing-cases
and musical instruments.

From incisions made into the trunk of the spruce fir-tree, a fine and
clear turpentine oozes, which, after being boiled in water, and
strained through a linen cloth, acquires a somewhat solid
consistence, and reddish brown colour; and is called Burgundy pitch.
This is employed as an ingredient in several kinds of ointments and
plasters: and is principally manufactured in Saxony.

The article called essence of spruce, which is used in making spruce


beer, is prepared from the branches of this tree, and from those of a
species nearly allied to it which grows in America.

249. The LARCH (Pinus laryx), a native of the Alps, and the
mountains of Germany, is a species of fir, which has its leaves in
tufts, and its cones oblong, and of somewhat oval shape, the
margins of the scales bent back, and jagged.

The cultivation of larch-trees has of late been much recommended


for adoption in this country, on account of the value of their timber,
which for strength and durability, is equal to most kinds of deal. It is
well calculated for masts, and the framework of vessels, being
capable of sustaining much greater pressure even than oak. For
wood-work constantly immersed in water, it is peculiarly calculated,
as, in such situations, it is asserted to become almost as hard as
stone. In Petersburg larch timber is applied to no other use than that
of ship-building. Line-of-battle ships are constructed of it in
Archangel, and these generally last about fifteen years; though, in
milder climates, it is imagined that they would last much longer.

For gates, pales, and similar work, exposed to the vicissitudes of


weather, they are admirably serviceable; and for flooring and other
internal purposes are at least equally durable. Buildings constructed
of larch timber are said to have continued sound for 200 years; and,
in some of the old palaces in Venice, there are beams of larch yet
existing that are as sound as when they were first placed. But the
very combustible nature of this wood renders it objectionable for
such uses. No wood with which we are acquainted affords more
durable staves for casks than larch; and, in the opinion of many
persons, it is further valuable by improving the flavour of the wine
contained in them. The wood is of delicate colour, not unlike the
cedar used for black-lead pencils, but is knotty almost throughout.

From the inner bark of the larch the Russians manufacture a soft
and fine kind of white gloves. The trunk, if tapped betwixt the
months of March and September, yields an extremely pure
turpentine, which has the name of Venice turpentine; and is of
considerable use in medicine. It is usually thinner than any other
kind of turpentine, and of clear, whitish, or yellowish colour. The
drug of this name, which is generally met with in the shops, is now
imported from New England, but was formerly brought from Venice.
A brown gummy substance, known in Russia by the name of
Orenburgh gum, is obtained by a curious process from the sap of
the tree. On the large branches of the larch are produced small,
sweetish grains, somewhat resembling sugar; which are frequently
substituted for the drug called manna (275).
The cultivation of the larch was first introduced into Britain towards
the conclusion of the seventeenth century. The trees will grow in
almost any soil; and the proper season for felling them is the month
of July. They, however, seldom attain any large size in this country;
and they are said to decay and become covered with moss, when
about forty years old.

250. The CYPRESS-TREE (Cupressus sempervirens) is a dark-


coloured evergreen, a native of the Levant, the leaves of which
are extremely small, and entirely cover all the slender branches,
lying close upon them so as to give them a somewhat
quadrangular shape.

In some of the trees the branches diminish gradually in length


from the bottom to the top, in such manner as to form a nearly
pyramidal shape.

In many of the old gardens in this country cypress-trees are still to


be found, but their generally sombre and gloomy appearance has
caused them, of late years, to be much neglected. They are,
however, very valuable on account of their wood, which is hard,
compact, and durable, of pale or reddish colour, with deep veins,
and pleasant smell. We are informed by Pliny that the doors of the
famous temple of Diana, at Ephesus, were of cypress wood, and
that, although they were 400 years old at the time when he wrote,
they appeared to be nearly as fresh as new. Indeed this wood was
so much esteemed by the ancients, that the image of Jupiter in the
capitol was made of it. The gates of St. Peter's church at Rome are
stated to have been of cypress, and to have lasted more than 1000
years, from the time of the Emperor Constantine until that of Pope
Eugenius the Fourth, when gates of brass were erected in their
stead. As this wood, in addition to its other qualities, takes a fine
polish, and is not liable to suffer from the attacks of insects, it was
formerly much esteemed for cabinet furniture. By the Greeks, in the
time of Thucydides, it was used for the coffins of eminent warriors;
and many of the chests which enclose Egyptian mummies are made
of it. The latter afford very decisive proof of its almost incorruptible
nature.

The name of this tree is derived from the island of Cyprus, in the
Mediterranean, where it still grows in great luxuriance. Its gloomy
hue caused it to be consecrated by the ancients to Pluto, and to be
used at the funerals of people of eminence. Pliny states that, in his
time, it was customary to place branches of the cypress-tree before
the houses in which persons lay dead.

251. The CASSAVA, or CASSADA (Jatropha manihot) is a South


American shrub, about three feet in height, with broad, shining,
and somewhat hand-shaped leaves, and beautiful white and
rose-coloured flowers.

It is a very remarkable circumstance, that the roots of the cassava, if


eaten raw, are a fatal poison both to man and beast, and that, when
prepared by heat, they yield a safe and valuable food; on which,
indeed, many both of the Indian and European inhabitants of South
America almost wholly subsist. The roots are the only edible parts of
the plant. These, which are white, soft, and farinaceous, from one to
two feet in length, and five or six inches in circumference, are dug
out of the earth, at a certain season of the year, washed, stripped of
their rind, and ground to a pulp. The juice, or poisonous part, is
pressed out, and carefully thrown away; as cattle, and other
animals, which have accidentally drunk of it, have almost instantly
died. The flour that remains, after pressure, is formed into thin
round cakes and baked. To an European, accustomed to other
bread, these, though sweetish, and not unpalatable, have an insipid
taste. If placed in close vessels, and preserved from the attacks of
insects, cassava bread may be kept for several months without
injury.
With the natives of South America, it is not unusual to throw a great
number of cakes of cassava together to heat, after which they soak
them in water, which causes a rapid fermentation to take place; and
from the liquor thus obtained, they make a very sharp and
disagreeable, but intoxicating beverage, which will not keep longer
than twenty-four hours without spoiling.

From the pure flour of cassava is formed the substance called


tapioca, which is frequently imported into this country, and is used
for jelly, puddings, and other culinary purposes. It is prepared from
the fibrous part of the roots by taking a small quantity of the pulp,
after the juice is extracted, and working it in the hand till a thick
white cream appears on the surface. This, being separated, and
washed in water, gradually subsides to the bottom. After the water is
poured off, the remaining moisture is dissipated by a slow fire, the
substance being constantly stirred, until at length it is formed into
grains about the size of sago (266). These become hard by keeping,
and are the purest and most wholesome part of the cassava.

The roots of another species of this shrub, called sweet cassava, are
usually eaten with butter, and merely after being roasted in hot
ashes. They have much the flavour of chesnuts, and are an
agreeable and nutritive food.

252. The TALLOW TREE (Croton sebiferum) is a native of China,


and in habit somewhat resembles a cherry-tree, but has shining
egg-shaped, and pointed leaves, that form tufts at the extremity
of the branches.

The fruit of this tree, from which the Chinese obtain a kind of tallow
for the manufacture of candles, is enclosed in a husk, not much
unlike that of the chesnut, and consists of three round white kernels.
All the preparation that is requisite is to melt these kernels, adding a
little oil, to render them softer and more pliant than they would
otherwise be. The candles made from this substance are very white,
but are sometimes coloured by adding a little vermilion. They are
more firm than those of tallow, but not equal in quality to candles
either of wax or spermaceti. The wicks that are used are not, like
ours, made of cotton, but consist of little rods of light, dry wood,
with the pith of a rush entwined round them.

253. INDIAN RUBBER, or CAOUTCHOUC, is the dried juice of a


large and much branched tree (Siphonia elastica, Fig. 60), which
grows in Guiana, and other parts of South America.

This tree has somewhat oval leaves, entire, veined, and smooth,
arranged in threes, and on long foot-stalks.

The flowers are small, in bunches, near the ends of the


branches, and the fruit is triangular.

It was not until about the year 1736, that this very extraordinary
natural production was made known in Europe. It is obtained by
making incisions through the bark of the tree, chiefly in wet weather.
From the wounds thus formed the juice flows abundantly. It is of
milky-white colour, and is conducted by a tube or leaf, supported by
clay, into a vessel placed to receive it. Some writers assert that, on
mere exposure to the air, it gradually hardens; and others that, for
this purpose, it goes through a certain process, which the Indians
keep a profound secret. It is usually brought to Europe in the shape
of pear-shaped bottles, which are formed by spreading the juice
over a mould of clay. These are exposed to a dense smoke, or to a
fire, till they become so dry as not to stick to the fingers; and then,
by certain instruments of iron or wood, they are ornamented on the
outside with various figures. This done, the clay in the inside is
moistened with water and picked out.
Indian rubber is remarkable for the flexibility and elasticity which it
acquires on attaining a solid state; and also for the numerous useful
purposes to which it is capable of being applied. By the Indians it is
sometimes formed into boots, which are impenetrable by water, and
which, when smoked, have the appearance of leather. Bottles are
made of it, to whose necks are fastened hollow reeds, through
which the liquor contained in them can be squirted at pleasure. One
of these, filled with water, is always presented to each of the guests
at their entertainments. Flambeaux are likewise formed of this
substance, which give a very brilliant light; and it is said that a torch
of Indian rubber, an inch and a half in diameter, and two feet long,
will burn twelve hours. The inhabitants of Quito prepare a species of
oil-cloth with the hardened juice of this tree.

The principal uses to which Indian rubber is applied by us are, for


the effacing of black-lead marks; for flexible syringes, tubes, and
other instruments used by surgeons and chemists; and for the
formation, by means of turpentine or linseed oil, of a varnish for air-
balloons.

Various experiments have been made to dissolve this substance, so


that it may assume its naturally elastic state, under any figure that
may be required. This has been effected by means of ether, but the
process is too expensive for common use. A simple method of
forming tubes of it is to split a piece of cane and to put between the
pieces a slip of whalebone. If the Indian rubber be cut into slips, and
twisted closely round the cane, and the heat of boiling water be
applied, the whole will become united into one piece or tube, from
which the whalebone first, and afterwards the cane, may easily be
separated.

It has been proved that cloth of all kinds may be made impenetrable
by water, if impregnated with the fresh juice of the Indian rubber
tree; and that boots, gloves, and other articles, made of cloth thus
prepared, may be joined without sewing, and only by moistening the
edges with the juice. These are not only more durable, but retain
their shape better than such as are made of the juice without any
connecting substance.

It has lately been ascertained that, in Prince of Wales's Island, and


also in Sumatra, there are trees of a class and order totally different
from that above described, which yield a juice similar to this, and
applicable to all the same purposes.

254. The CASTOR-OIL PLANT (Ricinus palma christi) is a native


both of the East and West Indies, and has a stem from five to
fifteen or sixteen feet in height, and large bluish-green leaves,
divided into seven lobes, serrated and pointed, the footstalks
long, and inserted into the disk.

The flowers are produced in a terminating spike, and the seed-


vessels are covered with spines, and contain each three flattish
oblong seeds.

It is to the seeds of this plant that we are indebted for the drug
called castor-oil. This is sometimes obtained by pressing the seeds,
in the same way as is practised with respect to oil of almonds (152).
But the mode chiefly adopted in the West Indies, whence we
principally import it, is first to strip the seeds of their husks or pods,
and then to bruise them in a mortar; afterwards they are tied in
linen bags, and boiled in water until the oil which they contain rises
to the surface; this is carefully skimmed off, strained to free it from
any accidental impurities, and bottled for use. The oil which is
obtained by boiling is considered more mild than that obtained by
pressure, but it sooner becomes rancid. The mildest and finest of the
Jamaica castor-oil is limpid, nearly colourless, and has scarcely more
taste or smell than good olive-oil.

The uses of castor-oil in medicine are well known.

The plant is sufficiently hardy to grow and ripen its seeds in the
open ground of gardens, in the south of England.
CLASS XXII.—DIŒCIA.

DIANDRIA.

255. WILLOW, OSIER, or WITHY.—Of this very extensive tribe nearly


fifty distinct species have been discovered in our own island. The
slender branches of many of these are applied to useful purposes,
but particularly for making baskets, bird-cages, and what is called
wicker-work; springles for fastening down thatch, wheels or traps for
catching lobsters and eels; hoops and crates. The wood is useful for
the handles of hatchets, prongs, spades, and other rural
implements; and also furnishes shoemakers with cutting and
whetting boards, on which they cut leather and sharpen the edges
of their knives.

As willows generally flourish in wet situations, some of the species


are planted with a view to prevent the banks of rivers and brooks
from being washed away by floods.

The bark of some kinds of willow has been applied, with effect, as a
substitute for Peruvian bark, in the cure of intermittent fevers. It has
also been esteemed useful in the tanning of leather; and, in
combination with alder, for striking a deep black colour, in the dyeing
of linen.

The bark of other species may be manufactured into paper. In the


year 1788, Mr. Greaves of Milbank, near Warrington, Lancashire,
made fifteen reams of coarse paper from the bark of withen twigs,
intermixed with a few nettles. The latter, however, he afterwards
discovered, would better have been left out, as there was in them a
woody substance, which does not well incorporate with other
vegetables. The paper he made was considerably cheaper than
paper of equal size and thickness made from ropes; and it was
found that pasteboard, for book covers, made of withen bark, would
be much cheaper than similar pasteboard manufactured from ropes.
The process by which this paper and pasteboard were manufactured
was as follows; the bark was stripped from the twigs in September,
the time at which they are usually cut for making white baskets; it
was then hackled, like flax or hemp, and dried in the sun, which
gave it somewhat the appearance of brown hemp: but this having
been attended with considerable trouble, other parts of the bark
were dried with the leaves, as they were stripped off from the twigs,
and were then submitted to the operation of the paper-mill.

The flowering branches of one species, the common sallow (Salix


cineria), are called palms, and are gathered by children, in many
parts of England, on Palm Sunday.

TRIANDRIA.

256. NUTMEGS are the kernels of a fruit produced in several


islands of the East Indies.

They are each surrounded by the spice called mace, and,


externally, by a husk about half an inch in thickness, which has
somewhat the appearance of a small peach (Fig. 80).

The nutmeg-tree (Myristica aromatica) is not unlike our cherry-


tree, both in growth and size. Its leaves are nearly oval, but
pointed, waved, obliquely nerved, of bright green colour above,
and whitish beneath. The flowers are small, and hang upon
slender stalks.
When this fruit is nearly ripe the husk opens at the end, and exposes
a net-work of scarlet mace. Underneath the mace is a black shell,
about as thick as that of a filbert, and very hard; and in this is
contained the nutmeg.

The gathering of nutmegs is performed by persons who ascend the


trees for that purpose, and pull the branches to them with long
hooks. The husks are stripped off in the woods, and the remaining
part of the fruit, with its surrounding mace, is taken home. After the
mace has been carefully stripped off, with a small knife, the nuts,
which are still covered with their woody shell, are dried, first in the
sun, and then upon a frame of split bamboos placed over a slow fire,
until, when shaken, the kernels are heard to rattle within the shells.
These now easily fly to pieces when beaten with small sticks; and
the nutmegs, being taken out, are soaked in sea-water and lime,
and are then thrown in great numbers together to heat, by which
their vegetating principle is destroyed. The nutmegs are finally
sorted into parcels, according to their quality, and packed in bags for
sale and exportation.

The nutmegs vended at the East India Company's sales in 1804,


amounted in weight to 117,936 pounds, and produced 54,733l.
exclusive of the duties. This kind of spice has long been employed
both for culinary and medicinal purposes. Distilled with water,
nutmegs afford a large portion of essential oil, which resembles, in
flavour, the spice itself. When heated and pressed they yield a
considerable quantity of limpid yellow oil. In the shops a thick and
fragrant kind is sold, which, though called oil of mace, is, in reality,
expressed from the nutmeg. The best oil of this description is
imported from the East Indies, in stone jars. Oil of nutmegs is chiefly
made from the imperfect fruit, and such as would be unfit for the
European market.
Mace, or the covering of the nutmeg, that lies betwixt the outer coat
and the shell, is an unctuous membrane, first of a light red, and
afterwards, when dried, and as we see it, of yellowish colour. After it
is taken from the shell it is exposed to the sun, then moistened with
sea-water, and finally so far dried as to allow of its being packed in
bales for exportation. In these it is pressed closely down, by which
its fragrance and peculiar qualities are preserved. Mace is liable to
seizure if imported in packages of less than 300 pounds' weight. We
usually see it in flakes each about an inch in length, and presenting
a great variety of ramifications. This spice has a very fragrant and
agreeable odour, and, to most persons, a pleasant, though
somewhat acrid, taste. It possesses nearly all the virtues of the
nutmeg, but with less astringency; and, like that, is employed in
numerous ways, both in culinary preparations and medicine.

In the island of Banda it is sometimes customary to boil the entire


fruit of the nutmeg-tree, and afterwards to preserve it in syrup, and
also to pickle it in spiced vinegar, in nearly the same manner as we
pickle walnuts. In several parts of the East the inhabitants preserve
the outer husk of the nutmeg as a sweetmeat, or eat it stewed with
other food.

257. The DATE is a fruit shaped somewhat like a large acorn,


and covered externally with a yellowish membrane or skin,
which contains a fine, soft, and sweetish pulp, and, in the
centre, an oblong, hard stone.

The trees (Phœnix dactylifera) which produce this fruit, grow


chiefly on the shores of the Mediterranean, are forty feet and
upwards in height, have an upright stem, marked through their
whole length with protuberances, and terminated at the summit
with a cluster of winged leaves or branches, each eight or nine
feet in length.
The cultivation of the date is attentively pursued on the African coast
of the Mediterranean; in several parts of Persia, Arabia, and even in
Spain. The latter country, however, is not sufficiently warm to ripen
the fruit in perfection, without the constant labour of the cultivator.
He is obliged to ascend the trees, from time to time, to examine the
flowers and turn them towards the sun. This is chiefly done in the
spring of the year; and, during the month of August, another and
much more dangerous operation is requisite, namely, to tie all the
branches into one bundle, and cover them over with broom. To
make this bundle, the person employed is obliged to leap, as it were,
over the flexible branches, for the purpose of surrounding and
uniting them with a cord. This operation over, he places a ladder at
the bottom of the tree, on which he stands to make a second band;
he then places his ladder on this second band, ascends and ties the
top with a third cord. His bundle being formed, he throws down his
instruments, replaces his ladder by a gradation contrary to the
former, and descends, from band to band, to the stem of the tree,
down which he slides to the bottom.

Among the Africans and Egyptians the date constitutes a principal


article of food, and, as such, it is considered both wholesome and
nutritive. Its name is a word, formed of dacte or dactylus, implying a
finger, from an imaginary resemblance which this fruit has to the end
of the finger. Although dates, in general, are of yellowish colour,
some are black, some white, and others brown: some also are
sweet, and others bitter. The best are called royal dates, and are
imported into this country from Tunis.

Each tree produces ten or twelve bunches of fruit, which, when


gathered, are hung up in a dry place, until so much of their moisture
is evaporated as to allow of their being packed in boxes for
exportation.
Nearly all the parts of the date-tree are useful. The wood, though of
spongy texture, is employed for the beams and rafters of houses,
and for implements of husbandry, which are said to be very durable.
The pith of the young trees is eaten, as well as the young and
tender leaves. From the old leaves and their stalks the women and
children of Valencia make mats, baskets, and other utensils; and
from other filamentous parts, ropes and different kinds of cordage
are manufactured. A considerable traffic is carried on in these
leaves, which, under the name of palms, are sent to Italy, to be used
in the grand religious ceremonies of Palm Sunday. In Persia an
ardent spirit is distilled from the fruit; and, in many places, the
stones are ground to make oil, and the paste that is left is given as
food to cattle and sheep.

PENTANDRIA.

258. MASTIC is a resinous substance, obtained from a low tree


or shrub (Pistacia lentiscus) which grows in the Levant.

It has alternate winged leaves, consisting of several pairs of


spear-shaped leaflets, and spikes of very small flowers, which
issue from the junction of the leaves with the branches.

The mode in which this resin is obtained is by making incisions


across the tree in different parts. From these the juice exudes in
drops, that are suffered to run upon the ground, and there to remain
until they are sufficiently hard to be collected for use. The season for
this process commences in the dry weather at the beginning of
August, and lasts until the end of September. The best mastic is that
imported from the island of Scio. We receive it in semi-transparent
grains of yellowish colour. These emit an agreeable smell when
heated; and, when chewed, they first crumble, and afterwards stick
together, and become soft and white like wax.
With the Turkish women it is customary to chew this resin for the
purpose of rendering their breath agreeable, and under a notion also
that it tends to make their teeth white, and to strengthen the gums.
They also mix it in fragrant waters, and burn it with other
odoriferous substances, by way of perfume. It was formerly much
used in medicine, as a remedy against pain in the teeth and gums;
and, dissolved in spirit of wine, as a relief in obstinate and long
continued coughs: but it is now almost wholly disused for these
purposes; and is chiefly employed in the composition of varnish, and
by dentists, for filling up the cavities of decayed teeth.

The wood of the mastic-tree is imported in thick knotty pieces,


covered externally with an ash-coloured bark. This wood is
accounted a mild, balsamic astringent; and a preparation of it, under
the name of aurum potabile, is strongly recommended, by some of
the German writers, in coughs, nausea, and weakness of the
stomach.
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