100% found this document useful (4 votes)
44 views81 pages

Data Structures Using C 2nd Edition A. K. Sharma Download

The document provides information about the second edition of 'Data Structures Using C' by A. K. Sharma, detailing its contents, chapters, and topics covered. It includes links to various related ebooks and emphasizes the enhancements made in this edition based on reader feedback. Key topics added include sparse matrices, recursion, hashing, and algorithms for trees and graphs.

Uploaded by

ycbbwsdm653
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
100% found this document useful (4 votes)
44 views81 pages

Data Structures Using C 2nd Edition A. K. Sharma Download

The document provides information about the second edition of 'Data Structures Using C' by A. K. Sharma, detailing its contents, chapters, and topics covered. It includes links to various related ebooks and emphasizes the enhancements made in this edition based on reader feedback. Key topics added include sparse matrices, recursion, hashing, and algorithms for trees and graphs.

Uploaded by

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

Data Structures Using C 2nd Edition A. K.

Sharma
pdf download

https://ebookname.com/product/data-structures-using-c-2nd-
edition-a-k-sharma/

Get the full ebook with Bonus Features for a Better Reading Experience on ebookname.com
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Data Structures with C Using STL 2nd Edition William H.


Ford

https://ebookname.com/product/data-structures-with-c-using-
stl-2nd-edition-william-h-ford/

C Data Structures A Laboratory Course Stefan Brandle

https://ebookname.com/product/c-data-structures-a-laboratory-
course-stefan-brandle/

Object Oriented Data Structures Using Java Chip Weems

https://ebookname.com/product/object-oriented-data-structures-
using-java-chip-weems/

International Control of Tritium for Nuclear


Nonproliferation and Disarmament Science and Global
Security Monograph Series 1st Edition Martin B.
Kalinowski
https://ebookname.com/product/international-control-of-tritium-
for-nuclear-nonproliferation-and-disarmament-science-and-global-
security-monograph-series-1st-edition-martin-b-kalinowski/
The Cyberspace Handbook Media Practice 1st Edition
Jason Whittaker

https://ebookname.com/product/the-cyberspace-handbook-media-
practice-1st-edition-jason-whittaker/

10 Less Democracy Why You Should Trust Elites a Little


More and the Masses a Little Less Garett Jones

https://ebookname.com/product/10-less-democracy-why-you-should-
trust-elites-a-little-more-and-the-masses-a-little-less-garett-
jones/

Modular Electricity Storage Benefits and Costs 1st


Edition Brent N. Mendell

https://ebookname.com/product/modular-electricity-storage-
benefits-and-costs-1st-edition-brent-n-mendell/

Long Term Durability of Structural Materials 1st


Edition J. Larsen-Basse

https://ebookname.com/product/long-term-durability-of-structural-
materials-1st-edition-j-larsen-basse/

International Law and Post Conflict Reconstruction


Policy 1st Edition Matthew Saul (Editor)

https://ebookname.com/product/international-law-and-post-
conflict-reconstruction-policy-1st-edition-matthew-saul-editor/
My Word Plagiarism and College Culture 1st Edition
Susan D. Blum

https://ebookname.com/product/my-word-plagiarism-and-college-
culture-1st-edition-susan-d-blum/
Data Structures Using C
This page is intentionally left blank.
Data Structures Using C
Second Edition

A. K. Sharma
Professor and Dean
YMCA University of Science and Technology

Delhi • Chennai
Copyright © 2013 Dorling Kindersley (India) Pvt. Ltd.
Licensees of Pearson Education in South Asia

No part of this eBook may be used or reproduced in any manner whatsoever without the publisher’s
prior written consent.

This eBook may or may not include all assets that were part of the print version. The publisher
reserves the right to remove any material in this eBook at any time.

ISBN 9788131792544
eISBN 9789332514225

Head Office: A-8(A), Sector 62, Knowledge Boulevard, 7th Floor, NOIDA 201 309, India
Registered Office: 11 Local Shopping Centre, Panchsheel Park, New Delhi 110 017, India
To
my parents,
wife Suman and daughter Sagun
This page is intentionally left blank.
Contents
Preface to the Second Edition xiii
Preface xiv
About the Author xv

Chapter 1: Overview of C 1
1.1 The History 1
1.2 Characters Used in C 2
1.3 Data Types 2
1.3.1 Integer Data Type (int) 2
1.3.2 Character Data Type (char) 3
1.3.3 The Floating Point (f loat) Data Type 3
1.4 C Tokens 4
1.4.1 Identifiers 4
1.4.2 Keywords 5
1.4.3 Variables 5
1.4.4 Constants 7
1.5 Structure of a C Program 8
1.5.1 Our First Program 8
1.6 printf() and scanf() Functions 8
1.6.1 How to Display Data Using printf() Function 9
1.6.2 How to Read Data from Keyboard Using scanf() 10
1.7 Comments 10
1.8 Escape Sequence (Backslash Character Constants) 11
1.9 Operators and Expressions 13
1.9.1 Arithmetic Operators 13
1.9.2 Relational and Logical Operators 14
1.9.3 Conditional Operator 16
1.9.4 Order of Evaluation of Expressions 17
1.9.5 Some Special Operators 18
1.9.6 Assignment Operator 18
1.9.7 Bitwise Shift Operators 19
1.10 Flow of Control 20
1.10.1 The Compound Statement 21
1.10.2 Selective Execution (Conditional Statements) 21
1.10.3 Repetitive Execution (Iterative Statements) 25
1.10.4 The exit() Function 27
1.10.5 Nested Loops 28
1.10.6 The Goto Statement (Unconditional Branching) 28
viii Data Structures Using C

1.11 Input–Output Functions (I/O) 30


1.11.1 Buffered I/O 31
1.11.2 Single Character Functions 32
1.11.3 String-based Functions 33
1.12 Arrays 34
1.13 Structures 34
1.13.1 Defining a Structure in C 35
1.13.2 Referencing Structure Elements 36
1.13.3 Arrays of Structures 36
1.13.4 Initializing Structures 37
1.13.5 Assignment of Complete Structures 37
1.13.6 Nested Structures 38
1.14 User-defined Data Types 39
1.14.1 Enumerated Data Types 40
1.15 Unions 42
1.16 Functions 43
1.16.1 Function Prototypes 44
1.16.2 Calling a Function 45
1.16.3 Parameter Passing in Functions 47
1.16.4 Returning Values from Functions 52
1.16.5 Passing Structures to Functions 52
1.17 Recursion 56
1.17.1 Types of Recursion 60
1.17.2 Tower of Hanoi 65

Chapter 2: Data Structures and Algorithms: An Introduction 72


2.1 Overview 72
2.2 Concept of Data Structures 73
2.2.1 Choice of Right Data Structures 74
2.2.2 Types of Data Structures 76
2.2.3 Basic Terminology Related with Data Structures 77
2.3 Design of a Suitable Algorithm 78
2.3.1 How to Develop an Algorithm? 78
2.3.2 Stepwise Refinement 80
2.3.3 Using Control Structures 81
2.4 Algorithm Analysis 85
2.4.1 Big-Oh Notation 86

Chapter 3: Arrays: Searching and Sorting 93


3.1 Introduction 93
3.2 One-dimensional Arrays 94
3.2.1 Traversal 95
3.2.2 Selection 96
3.2.3 Searching 98
Contents ix

3.2.4 Insertion and Deletion 105


3.2.5 Sorting 109
3.3 Multi-dimensional Arrays 130
3.4 Representation of Arrays in Physical Memory 134
3.4.1 Physical Address Computation of Elements of One-dimensional Arrays 135
3.4.2 Physical Address Computation of Elements of Two-dimensional Arrays 136
3.5 Applications of Arrays 138
3.5.1 Polynomial Representation and Operations 138
3.5.2 Sparse Matrix Representation 141

Chapter 4: Stacks and Queues 151


4.1 Stacks 151
4.1.1 Stack Operations 152
4.2 Applications of Stacks 156
4.2.1 Arithmetic Expressions 156
4.3 Queues 170
4.3.1 Queue Operations 171
4.3.2 Circular Queue 176
4.3.3 Priority Queue 181
4.3.4 The Deque 185

Chapter 5: Pointers 197


5.1 Introduction 197
5.1.1 The ‘&’ Operator 197
5.1.2 The ‘*’ Operator 198
5.2 Pointer Variables 198
5.2.1 Dangling Pointers 202
5.3 Pointers and Arrays 203
5.4 Array of Pointers 208
5.5 Pointers and Structures 208
5.6 Dynamic Allocation 210
5.6.1 Self Referential Structures 215

Chapter 6: Linked Lists 227


6.1 Introduction 227
6.2 Linked Lists 227
6.3 Operations on Linked Lists 231
6.3.1 Creation of a Linked List 231
6.3.2 Travelling a Linked List 236
6.3.3 Searching a Linked List 241
6.3.4 Insertion in a Linked List 243
6.3.5 Deleting a Node from a Linked List 250
x Data Structures Using C

6.4 Variations of Linked Lists 253


6.4.1 Circular Linked Lists 254
6.4.2 Doubly Linked List 258
6.5 The Concept of Dummy Nodes 264
6.6 Linked Stacks 266
6.7 Linked Queues 270
6.8 Comparison of Sequential and Linked Storage 274
6.9 Solved Problems 274

Chapter 7: Trees 282


7.1 Introduction 282
7.2 Basic Terminology 284
7.3 Binary Trees 285
7.3.1 Properties of Binary Trees 286
7.4 Representation of a Binary Tree 287
7.4.1 Linear Representation of a Binary Tree 287
7.4.2 Linked Representation of a Binary Tree 289
7.4.3 Traversal of Binary Trees 291
7.5 Types of Binary Trees 298
7.5.1 Expression Tree 298
7.5.2 Binary Search Tree 303
7.5.3 Heap Trees 319
7.5.4 Threaded Binary Trees 340
7.6 Weighted Binary Trees and Huffman Algorithm 352
7.6.1 Huffman Algorithm 354
7.6.2 Huffman Codes 356
7.7 Dynamic Dictionary Coding 360

Chapter 8: Graphs 365


8.1 Introduction 365
8.2 Graph Terminology 366
8.3 Representation of Graphs 368
8.3.1 Array-based Representation of Graphs 368
8.3.2 Linked Representation of a Graph 371
8.3.3 Set Representation of Graphs 373
8.4 Operations of Graphs 373
8.4.1 Insertion Operation 374
8.4.2 Deletion Operation 379
8.4.3 Traversal of a Graph 384
8.4.4 Spanning Trees 396
8.4.5 Shortest Path Problem 401
8.5 Applications of Graphs 408
Contents xi

Chapter 9: Files 412


9.1 Data and Information 412
9.1.1 Data 412
9.1.2 Information 412
9.2 File Concepts 413
9.3 File Organization 415
9.4 Files in C 416
9.5 Files and Streams 416
9.6 Working with Files Using I/O Stream 418
9.6.1 Opening of a File 418
9.6.2 Unformatted File I/O Operations 419
9.6.3 Formatted File I/O Operations 425
9.6.4 Reading or Writing Blocks of Data in Files 426
9.7 Sequential File Organization 430
9.7.1 Creating a Sequential File 430
9.7.2 Reading and Searching a Sequential File 431
9.7.3 Appending a Sequential File 431
9.7.4 Updating a Sequential File 437
9.8 Direct File Organization 442
9.9 Indexed Sequential Organization 445
9.9.1 Searching a Record 445
9.9.2 Addition/Deletion of a Record 446
9.9.3 Storage Devices for Indexed Sequential Files 447
9.9.4 Multilevel Indexed Files 448
9.10 Choice of File Organization 448
9.11 Graded Problems 451

Chapter 10: Advanced Data Structures 459


10.1 AVL Trees 459
10.1.1 Searching an AVL Tree 461
10.1.2 Inserting a Node in an AVL Tree 462
10.2 Sets 468
10.2.1 Representation of Sets 469
10.2.2 Operations on Sets 470
10.2.3 Applications of Sets 476
10.3 Skip Lists 478
10.4 B-Trees 480
10.4.1 Searching a Key in a B-Tree 482
10.4.2 Inserting a Key in a B-Tree 483
10.4.3 Deleting a Key from a B-Tree 484
10.4.4 Advantages of B-Trees 487
xii Data Structures Using C

10.5 Searching by Hashing 489


10.5.1 Types of Hashing Functions 490
10.5.2 Requirements for Hashing Algorithms 491
10.5.3 Overflow Management (Collision Handling) 491

Appendix A ASCII Codes (Character Sets) 494


Appendix B Table of Format Specifiers 495
Appendix C Escape Sequences 496
Appendix D Trace of Huffman Algorithm 497

Index 501
Preface to the
Second Edition
I have been encouraged by the excellent response given by the readers to the first edition of the book to
work on the second edition. As per the feedback received from the teachers of the subject and the input
provided by the team at Pearson Education, the following topics in various chapters of the book have
been added:
1. Sparse matrices
2. Recursion
3. Hashing
4. Weighted binary trees
a. Huffman algorithm
5. Spanning trees, minimum cost spanning trees
a. Kruskal algorithm
b. Prims algorithm
6. Shortest path problems
a. Warshall’s algorithm
b. Floyd’s algorithm
c. Dijkstra’s algorithm
7. Indexed file organization
While revising the book, the text has been thoroughly edited and the errors found thereof have been
corrected. More examples on important topics have been included.
I hope the readers will like this revised edition of the book and, as before, will provide their much
needed feedback and comments for further improvement.

Acknowledgements
I am thankful to Khushboo Jain and Anuradha Pillai for helping me in preparing the solution manual
of the book.

A. K. Sharma
Preface
As a student, programmer, and teacher of computer engineering, I find ‘Data Structures’ a core course of
computer engineering and particularly central to programming process.
In fact in our day-to-day life, we are confronted with situations such as where I would keep a bunch
of keys, a pen, coins, two thousand rupees, a chalk, and five hundred thousand rupees.
I would keep the bunch of keys and coins in the left and right pockets of my pants, respectively. The
pen gets clipped to the front pocket of the shirt whereas two thousand rupees would go into my ticket
pocket. I would definitely put the five hundred thousand rupees into a safe, i.e., under the lock and key.
While teaching, I will keep the chalk in hand. The decision of choosing the places for these items is based
on two factors: ease of accessibility and security.
Similarly, given a problem situation, a mature programmer chooses the most appropriate data
structures to organize and store data associated with the problem. The reason being that the intel-
ligent choice of data structures will decide the fate of the software in terms of effectiveness, speed
and efficiency—the three most important much-needed features for the success of a commercial
venture.
I have taught ‘Data Structures’ for more than a decade and, therefore, the demand to write a book on
this subject was there for quite some time by my students and teacher colleagues.
The hallmark of this book is that it would not only help students to understand the concepts govern-
ing the data structures but also to develop a talent in them to use the art of discrimination to choose the
right data structures for a given problem situation. In order to provide a hands-on experience to budding
software engineers, implementations of the operations defined on data structures using ‘C’ have been
provided. The book has a balance between the fundamentals and advanced features, supported by solved
examples.
This book would not have been possible without the well wishes and contribution of many people
in terms of suggestions and useful remarks provided by them during its production. I record my
thanks to Dr Ashutosh Dixit, Anuradha Pillai, Sandya Dixit, Dr Komal Bhatia, Rosy Bhatia, Harsh, and
Indu Grover.
I am indebted to my teachers and research guides, Professor J. P. Gupta, Professor Padam Kumar,
Professor Moinuddin, and Professor D. P. Agarwal, for their encouragement. I am also thankful to
my friends, Professor Asok De, Professor Qasim Rafiq, Professor N.S. Gill, Rajiv Kapur and Professor
Rajender Sahu, for their continuous support and useful comments.
I am also thankful to various teams at Pearson who made this beautiful book happen.
Finally, I would like to extend special thanks to my parents, wife Suman and daughter Sagun for
saying ‘yes’ for this project when both wanted to say ‘no’. I know that I have stolen some of the quality
time which I ought to have spent with them.
Some errors might have unwittingly crept in. I shall be grateful if they are brought to my notice.
I would also be happy to acknowledge suggestions for further improvement of this book.

A. K. Sharma
About the Author
A. K. Sharma is currently Chairman, Department of Computer Engineering, and
Dean of Faculty, Engineering and Technology at YMCA University of Science and
Technology, Faridabad. He is also a member of the Board of Studies committee of
Maharshi Dayanand University, Rohtak. He has guided ten Ph.D. theses and has
published about 215 research papers in national and international journals of re-
pute. He heads a group of researchers actively working on the design of different
types of ‘Crawlers.
This page is intentionally left blank.
Overview of C
1
Chapter

• 1.1 The History


• 1.2 Characters Used in C
• 1.3 Data Types
• 1.4 C Tokens
CHapTER OuTlInE

• 1.5 Structure of a C Program


• 1.6 printf() and scanf() Functions
• 1.7 Comments
• 1.8 Escape Sequence (Backslash Character Constants)
• 1.9 Operators and Expressions
• 1.10 Flow of Control
• 1.11 Input–Output Functions (I/O)
• 1.12 Arrays
• 1.13 Structures
• 1.14 User-defined Data Types
• 1.15 Unions
• 1.16 Functions
• 1.17 Recursion

1.1 THE HISTORY


In 1971 Dennis Ritchi, a system programmer from Bell laboratories, developed a very powerful
language called C for writing UNIX, a large and complex operating system. Even the compiler of 'C'
was written in C. In fact, it is a high level language that not only supports the necessary data types
and data structures needed by a normal programmer but it can also access the computer hardware
through specially designed declarations and functions and, therefore, it is often called as a “middle-
level” language.
It is popular because of the following characteristics:
n Small size

n Wide use of functions and function calls

n Loose typing

n Bitwise low level programming support

n Structured language

n Wide use of pointers to access data structures and physical memory of the system

Besides the above characteristics, the C programs are small and efficient. A ‘C’ program can be
compiled on variety of computers.
2 Data Structures Using C

1.2 CHaRaCTERS uSED In C


The set of characters allowed in C consists of alphabets, digits, and special characters as listed below:
(i) Letters: Both upper case and lower case letters of English:
A, B, C, .... X, Y, and Z
a, b, c, .... x, y, and z
(ii) Decimal digits:
0, 1, 2, .... 7, 8, 9
(iii) Special characters:
! * 1 \ “ <<
#(5 ! {
%) ; “ /
^_ [ :, ?
&_ ]’ . blank

1.3 DaTa TYpES


Every program specifies a set of operations to be done on some data in a particular sequence. However,
the data can be of many types such as a numbers, characters, floating points, etc. C supports the following
simple data types: Integer data type, character data type, floating point data type.

1.3.1 Integer Data Type (int)


An integer is an integral whole number without a decimal point. These numbers are used for counting.
Examples of integers are:
923
47
5
15924
−56
2245
C allows four types of representation of integers, i.e., integer, long integer, short integer, and unsigned
integer.
n Integer: An integer is referred to as int. It is stored in one word of the memory.

n Long integer: A long integer is referred to as long int or simple long. It is stored in 32 bits and

does not depend upon the word size of the memory.


n Short integer: A short integer is referred to as short int or simple short. It is stored in 16 bits and

does not depend upon the size of the memory.


n Unsigned integers: C supports two types of unsigned integers: the unsigned int and the unsigned short.

The unsigned int is stored in one word of the memory whereas the unsigned short is stored in
16 bits and does not depend upon the word size of the memory.
Examples of invalid integers are:
(i) 9, 24, 173 illegal-comma used
(ii) 5.29 illegal-decimal point used
(iii) 79 248 blank used
Overview of C 3

1.3.2 Character Data Type (char)


It is a non-numeric data type consisting of single alphanumeric character enclosed between a pair of
apostrophes, i.e., single quotation marks.
Examples of valid character type are:
‘A’
‘N’
‘*’
‘7’
It may be noted that the character ‘7’ is different from the numeric value 7. In fact, former is of type
char and later of type int. Each character has a numeric code, i.e., the ASCII code. For instance, the
ASCII code for the character ‘A’ is 65 and that of ‘*’ is 42. A table of ASCII codes is given in Appendix A.
A character data type is referred to as char. It is stored in one byte of memory. However, the
representation varies from computer to computer. For instance, some computers support signed as well
as unsigned characters. The signed characters can store integer values from 2128 to 1127 whereas the
unsigned characters store ASCII codes from 0 to 255.

1.3.3 The Floating point (float) Data Type


A floating point number is a real number which can be represented in two forms: decimal and exponent
forms. Floating point numbers are generally used for measuring quantities.
(1) Decimal form: The floating point number in this form has a decimal point. Even if it is an
integral value, it must include the decimal point.
Examples of valid “decimal form” numbers are:
973.24
849.
73.0
282349.24
9.0004
(2) Exponent form: The exponent form of floating point number consists of the following parts:
<integer>. <fraction> e <exponent>
Examples of valid floating point numbers are:
3.45 e 7
0.249 e 26
It may be noted that exponent form is a scientific notation wherein the number is broken into two
parts: mantissa and exponent. The mantissa is a floating point number of decimal form. The exponent
part starts with a letter ‘e’ followed by an integer (signed or unsigned).
For example, the number 324.5 can be written as 3.245 times 102. In exponential form, the number
is represented as 3.245 e2. In fact, the base 10 has been replaced by the character e (or E).
The utility of exponential form is that very small numbers can be easily represented by this notation
of floating points.
For example, the number 0.00001297 can be written as 0.1297 e24 or as 12.97 e26 or as 129.7 e27.
C allows the following two data types for floating prints:
n float: These types of numbers are stored in 32 bits of memory.

n double: The numbers of double data type are stored in 64 bits of memory.
4 Data Structures Using C

A summary of C basic data types is given the Table 1.1. From this table, it may be observed that charac-
ter and integer type data can also be declared as unsigned. Such data types are called unsigned data types.
In this representation, the data is always a positive number with range starting from 0 to a maximum
value. Thus, a number twice as big as a signed number can be represented through unsigned data types.

n Table 1.1 Basic data types in C


C data type Size lower bound upper bound Represents
Char 1 – – Character
Unsigned Char 1 0 255 Character
Short (int) 2 232768 132767 Whole number
Unsigned Short int 2 0 65535 Whole number
Long int 4 2,147,438,648 2,141,438,647 Whole number
Float 4 −3.4 3 10 ±38 13.4 3 10 ±38 Real number
Double 8 −1.7 3 10 ±308
11.7 3 10 ±308
Real number

1.4 C TOKEnS
A token is a group of characters that logically belong together. In fact, a programmer can write a program
by using tokens. C supports the following types of tokens:
n Identifiers

n Keywords

n Constants

n Variables

1.4.1 Identifiers
Symbolic names can be used in C for various data items. For example, if a programmer desires to store a
value 27, then he can choose any symbolic name (say, ROLL) and use it as given below:
ROLL = 27;
Where ROLL is a memory location and the symbol ‘5’ is an assignment operator.
The significance of the above statement is that ‘ROLL’ is a symbolic name for a memory location
where the value 27 is being stored. A symbolic name is generally known as an identifier.
The identifier is a sequence of characters taken from C character set. The number of characters in
an identifier is not fixed though most of the C compilers allow 31 characters. The rules for the formation
of an identifier are:
n An identifier can consist of alphabets, digits and and/or underscores.

n It must not start with a digit.

n C is case sensitive, i.e., upper case and lower case letters are considered different from each other.

n An identifier can start with an underscore character. Some special C names begin with the

underscore.
n Special characters such as blank space, comma, semicolon, colon, period, slash, etc. are not allowed.

n The name of an identifier should be so chosen that its usage and meaning becomes clear. For

example, total, salary, roll no, etc. are self explanatory identifiers.
Overview of C 5

Examples of acceptable identifiers are:


TOTAL
Sum
Net_sal
P123
a_b_c
total
_sysreg

Examples of unacceptable identifiers are:


Bas ic (blank not allowed)
H, rent (special character `, ‘ included)
It may be noted here that TOTAL and total are two different identifier names.

1.4.2 Keywords
A keyword is a reserved word of C. This cannot be used n Table 1.2 Standard keywords in C
as an identifier by the user in his program. The set of C
auto double int struct
keywords is given in Table 1.2.
break else long switch
1.4.3 Variables case enum register typedef
A variable is the most fundamental aspect of any com- char extern return union
puter language. It is a location in the computer memory const float short unsigned
which can store data and is given a symbolic name for continue for signed void
easy reference. The variables can be used to hold differ-
default goto sizeof volatile
ent values at different times during a program run. To
do if static while
understand this concept, let us have a look at the follow-
ing set of statements:
Total 5 500.25; ...(i)
Net 5 Total 2 100.00; ...(ii)
In statement (i), value 500.25 has been stored in a memory location called Total. The variable Total
is being used in statement (ii) for the calculation of another variable Net. The point worth noting is that
‘the variable Total is used in statement (ii) by its name not by its value’.
Before a variable is used in a program, it has to be defined. This activity enables the compiler to
make available the appropriate amount of space and location in the memory. The definition of a variable
consists of its type followed by the name of the variable. For example, a variable called Total of type float
can be declared as shown below:
float Total;

Similarly, the variable net of type int can also be defined as shown below:
int Net;
Examples of valid variable declarations are:
(i) int count;
(ii) int i, j, k;
(iii) char ch, first;
6 Data Structures Using C

(iv) float Total, Net;


(v) long int sal;
(vi) double salary.
val
Let us now look at a variable declaration
from a different perspective. Whenever a variable
(say, int val) is declared, a memory location called int val;
val is made available by the compiler as shown in
Figure 1.1.
Thus, val is the name associated by the com-
piler to a location in the memory of the computer. Fig. 1.1 Memory allocated to variable val
Let us assume that, at the time of execution, the
physical address of this memory location (called
val) is 4715 as shown in Figure 1.2.
Now, a point worth noting is that this memory loca-
tion is viewed by the programmer as a variable called val
and by the computer system as an address 4715. The pro- 4715 val
grammer can store a value in this location with the help of
an assignment operator, i.e., ‘5’. For example, if the pro-
grammer desires to store a value 100 into the variable val,
he can do so by the following statement:
val 5 100;
Once the above statement is executed, the memory Fig. 1.2 The physical address of val
location called val gets the value 100 as shown in Figure 1.3.
C allows the initialization of variables even at the time
of declaration as shown below:
int val 5 100;

From Figure 1.3, we can see that besides its type a variable has three entities associated with it, i.e.,
the name of variable (val), its physical address (4715), and its contents (100). The content of a variable
is also called its rvalue whereas the physical address of the variable is called its lvalue. Thus, lvalue
and rvalue of variable val are 4715 and 100, respectively. The lvalue is of more importance because it
is an expression that should appear on the left hand side of assignment operator because it refers to the
variable or object.

Memory

4715 100 val


Physical address
(lvalue) Name of the
variable
Contents (rvalue)

Fig. 1.3 The contents of a variable (rvalue)


Overview of C 7

1.4.4 Constants
A constant is a memory location which can store data in such a manner that its value during execu-
tion of a program does not change. Any attempt to change the value of a constant will result in an
error message. A constant in C can be of any of the basic data types, i.e., integer constant, float-
ing point constant, and character constant. const qualifier is used to declare a constant as shown
below:
const <type> <name> 5 <val>;
where
const: is a reserved word of C
<type>: is any of the basic data types
<name>: is the identifier name
<val>: is the value to be assigned to the constant.

(1) Integer constant: It is a constant which can be assigned integer values only. For example, if we
desire to have a constant called rate of type integer containing a fixed value 50, then the follow-
ing declaration can be used:
const int rate 5 50;
The above declaration means that rate is a constant of type integer having a fixed value 50. Consider
the following declaration:
const int rate;
rate 5 50;
The above initialization of constant rate is illegal. This is because of the reason that a constant can-
not be initialized for a value at a place other than where it is declared. It may be further noted that if a
program does not change or mutates\a constant or constant object then the program is called as const
correct.
(2) Floating point constant: It is a constant which can be assigned values of real or floating point
type. For example, if it is desired to have a constant called Pi containing value 3.1415, then the
following declaration can be used.
const float Pi = 3.1415;

The above declaration means that Pi is a constant of type float having a fixed value 3.1415. It may be
noted here that by default a floating point constant is of type double.
(3) Character constant: A character constant can contain a single character of information. Thus,
data such as ‘Y’ or ‘N’ is known as a character constant. Let us assume that it is desired to have a
constant called Akshar containing the character ‘Q’; following declaration can be used to obtain
such a constant.
const char Akshar = ‘Q’;
The above declaration means that Akshar is a constant of type char having a fixed value ‘Q’.
A sequence of characters enclosed within quotes is known as a string literal. For example, the
character sequence “computer” is a string literal. When a string literal is assigned to an identifier
declared as a constant, then it is known as a string constant. In fact, a string is an array of
characters. Arrays are discussed later in the chapter.
8 Data Structures Using C

1.5 STRuCTuRE OF a C pROGRaM


A simple program in C can be written as a module. More complex programs can be broken into sub-
modules. In C, all modules or subprograms are referred to as functions.
The structure of a typical C program is given below:
main ()
{
....;
....;
....;
}

Note:
(i) C is a case sensitive language, i.e., it distinguishes between upper case and lower case characters.
Thus, main() is different from Main(). In fact, most of the characters used in C are lowercase.
Hence, it is safest to type everything in lower case except when a programmer needs to capitalize
some text.
(ii) Every C program has a function called main followed by parentheses. It is from here that
program execution begins. A function is basically a subprogram and is complete in itself.
(iii) The task to be performed by a function is enclosed in curly braces called its body, i.e., {}.
These braces are equivalent to begin and end keywords used in some other languages like
Pascal. The body of function contains a set of statements and each statement must end with
a semicolon.

1.5.1 Our First program


Let us break the myth that C is a difficult language to start with. Without going into the details, the
beginner can quickly start writing the program such as given below:
#include <stdio.h>
main()
{
puts (“This is my first program”);
}

The above program displays the following text on the screen:


This is my first program.

1.6 printf() anD scanf() FunCTIOnS


C uses printf() and scanf() functions to write and read from I/O devices, respectively. These
functions have been declared in the header file called stdio.h.
Let us use printf() function to rewrite our first program. The modified program is given
below:
#include <stdio.h>
main()
{
Overview of C 9
printf (“This is my first program”);
}

This program displays the following message on the screen:


This is my first program.
In fact, any text written within the pair of quotes (“ ”) is displayed as such by printf() function on
the screen. However, this function is much more powerful than puts() in the sense that it can display
all types of data on the screen as explained below.

1.6.1 How to Display Data using printf() Function


An integer, stored in a variable, can be displayed on the screen by including a format specifier (%d)
within a pair of quotes as shown below:
#include <stdio.h>
main()
{
int age 5 25;
printf (“%d”, age);
}

The above program does the following:


(1) Declares a variable age of type int.
(2) Initializes age to 25, an integer value.
(3) Specifies %d, a format specifier indicating that an integer is to be displayed by printf() and
the data is stored in the variable called age.
It may noted that printf() has two arguments separated by a comma, i.e., format specifier written
within quotes and the variable age. It may be further noted that both messages and format specifiers can
be included within the pair of quotes as shown below:
printf (“ The age of student 5 %d”, age);

The above statement would display the following data on the screen:
The age of student = 25
Thus, the text between the quotes has been displayed as such but for %d, the data stored in the
variable age has been displayed.
A float can be displayed on the screen by including a format specifier (%f) within the pair of quotes
as shown below:
float rate = 9.5;
printf (“The rate of provident fund = %f”, rate);

The above statements would produce the following display:


The rate of provident fund 5 9.5
A char can be displayed by including a format specifier (%c) within the pair of quotes as shown
below:
char ch 5 `A’
printf (“The first alphabet is: %c”, ch);
10 Data Structures Using C

Obviously, the output of the above set of statements would be:


The first alphabet is: A.
The other specifiers which can be used in printf() function are given in Appendix B.

1.6.2 How to Read Data from Keyboard using scanf()


Similar to printf() function, scanf() function also uses the %d, %f, %c, and other format specifiers
to specify the kind of data to be read from the keyboard.
However, it expects the programmer to prefix the address operator `&’ to every variable written in
the argument list as shown below:
int roll;
scanf (“%d”, & roll);

The above set of statements declares the variable roll of type int, and reads the value for roll from
the keyboard. It may be noted that ‘&’, the address operator, is prefixed to the variable roll. The reason for
specifying ‘&’ would be discussed later in the book.
Similarly, other format specifiers can be used to input data from the keyboard.
Example 1: Write an interactive program that reads the marks secured by a student for four subjects
Sub1, Sub2, Sub3, and Sub4, the maximum marks of a subject being 100. The program shall compute
the percentage of marks obtained by the student.
Solution: The scanf() and prinf() functions would be used to do the required task. The required
program is as follows:
#include <stdio.h>
main()
{
int sub1, sub2, sub3, sub4;
float percent;
printf (“Enter the marks for four subjects:”);
scanf (“%d %d %d %d”,&sub1, &sub2, &sub3, &sub4);
percent 5 (sub1 1 sub2 1 sub3 1 sub4)/ 400.00*100;
printf (“The percentage 5 %f”, percent);
}

For input data 45 56 76 90, the above program computes the percentage and displays the following output:
The percentage 5 66.750000
Though the output is correct, but it has displayed unnecessary four trailing zeros. This can be con-
trolled by using field width specifiers discussed later in the chapter.

1.7 COMMEnTS
A comment can be added to the program by enclosing the text between the pair / * ... * /, i.e.,
the pair ‘/*’ indicates the beginning of the comment whereas the pair ‘*/’ marks the end of it. It is also
known as multiple line comment. For example, the following line is a comment:
Overview of C 11
/* This is my first program */

Everything written within `/*´ and `*/´ is ignored by the compiler. A comment written in this
fashion can overflow to multiple lines as shown below:
/* This is an illustration of multiple line comment. The C compiler ignores
these lines. A programmer can use comment lines for documentation of his
programs*/

In fact, a comment is a non-executable statement in the program.

1.8 ESCapE SEQuEnCE (BaCKSlaSH CHaRaCTER COnSTanTS)


C has some special character constants called backslash character constants. These are unprintable ASCII
characters which can perform special functions in the output statements. A backslash character constant
is nothing but a back slash (‘\’) character followed by another character.
For example, “\n” can be used in a printf() statement to send the next output to the beginning
of the next line.
Consider the following program:
#include <stdio.h >
main()
{
printf(“A backslash character constant”);
printf(“prints the output on the next line.”);
}

The output of this program would be:


A backslash character constant prints the output on the next line.
It may be noted that though two separate printf() statements were written in the above program,
the output has been displayed on the same line.
In order to display the text in two lines, the “\n” character constant should be placed either at the
end of the text in the first printf() statement or at the beginning of the text in the second printf()
statement.
Consider the following modified program:
#include <stdio.h>
main()
{
printf(“A backslash character constant”);
printf(“\n prints the output on the next line.”);
}

The character constant “\n” has been placed at the beginning of the text of the second printf()
statement and, therefore, the output of the program would be:
A back slash character constant
prints the output on the next line.
12 Data Structures Using C

Some other important backslash constants are listed below:

Backslash character constant Meaning


\t tab
\b backspace
\a bell (alert)
\n newline character
Note:
The backslash characters are also known as escape sequences; such characters can be used within
apostrophes or within double quotes.
(1) ’\t’ (tab): This character is called a tab character. Whenever it is inserted in an output state-
ment, the display moves over to the next present tab stop. Generally, a tab is of 8 blank spaces on
the screen. An example of usage of character ‘\t’ is given below:
#include <stdio.h>
main()
{
printf(“\n hello \t Comp-Boy”);
}

The output of the above statement would be on the new line with spacing as shown below:
hello Comp-Boy
(2) ’\b’ (Backspace): This character is also called backspace character. It is equivalent to the back-
space key symbol ( )available on the computer or typewriter. It moves one column back-
ward and positions the cursor on the character displayed on that column. An example of usage
of character '\b' is given below:
#include <<stdio.h
main()
{
printf(“\n ASHOKA\b-”);
}

The output of the above statement would be:


ASHOK-
We can see that the trailing letter ‘A’ has been overwritten by the character `-’ at the end of the
string constant <ASHOKA> the reason being that `\b’ moved the curser one column backward, i.e., at ‘A’
and printf() printed the character `-’ on that column position.
(3) ’\a’ (Alert): This character is also called alert or bell character. Whenever it is inserted in an
output statement, it sounds a bell which can be heard by the user sitting on the computer termi-
nal. It can be used in a situation where the programmer wants to catch the attention of the user
of this program. An example of usage of ‘\a’ character is given below:
#include <stdio.h>
main()
{
printf(“\n Error in data \a”);
}
Overview of C 13

The output of the above statement would be the following message on the screen and a sounding of
a bell on the system speaker.
Error in data

(4) ’\n’ (new line): As discussed earlier, this character is called newline character. Wherever it
appears in the output statement, the immediate next output is taken to the beginning of the next
new line on the screen. Consider the statement given below:
#include <stdio.h>
main()
{
printf(“\n This is \n a test.”);
}

The output of this statement would be:


This is
a test.

1.9 OpERaTORS anD EXpRESSIOnS


An operator is a symbol or letter used to specify a certain operation on variables in a program. For
example, the symbol ‘+’ is an add operator that adds two data items called operands.
Expressions: An expression is a combination of operands (i.e., constants, variables, numbers)
connected by operators and parenthesis. For example, in the expression given below A and B are operands
and ‘+’ is an operator.
A + B

C supports many types of operators such as arithmetic, relational, logical, etc. An expression that
involves arithmetic operators is known as an arithmetic expression. The computed result of an arithmetic
expression is always a numerical value. The expression which involves relational and/or logical operators
is called as a boolean expression or logical expression. The computed result of such an expression is a
logical value, i.e., either 1 (True) or 0 (False).
The rules of formation of an expression are:
n A signed or unsigned constant or variable is an expression.

n An expression connected by an operator to a variable or a constant is an expression.

n Two expressions connected by an operator is also an expression.

n Two operators should not occur in continuation.

1.9.1 arithmetic Operators


The valid arithmetic operators supported by C are given in Table 1.3.

1.9.1.1 Unary Arithmetic Operators A unary operator requires only one operand or data item.
The unary arithmetic operators supported by C are unary minus (‘-’), increment (‘++’), and decrement
(‘--’). As compared to binary operators, the unary operators are right associative in the sense that they
evaluate from right to left.
14 Data Structures Using C

n Table 1.3 Arithmetic operators


Symbol Stands for Example
1 addition x1y
2 subtraction x2y
* multiplication x *y
/ division x/y
% modulus or remainder x%y
22 decrement 22x
x22
11 increment x11

The unary minus operator is written before a numerical value, variable or an expression. Examples
of usage of unary minus operator are:
(i) 257 (ii) 22.923 (iii) 11x (iv) 22(a*b) (v) 8*(22(a + b))
It may be noted here that the result of application of unary minus on an operand is the negation of
its operand.
The operators ‘++’ and ‘--’ are unique to C. These are called increment and decrement operators,
respectively. The increment operator ‘++’ adds 1 to its operand. Therefore, we can say that the following
expressions are equivalent.
i = i + 1 ≡ ++i;
For example, if the initial value of i is 10 then the expression ++i will increment the contents of
i to 11. Similarly, the decrement operator ‘--’ subtracts 1 from its operand. Therefore, we can say that
the following expressions are equivalent:
j = j - 1 ≡ --j;
For example, if the initial value of j is 5 then the expression --j will decrement the contents of j to 4.
The increment and decrement operators can be used both as a prefix and as a postfix to a variable
as shown below:
++ x or x++
--y or y--

As long as the increment or decrement operator is not used as part of an expression, the prefix and
postfix forms of these operators do not make any difference. For example, ++x and x++ would produce
the same result. However, if such an operator is part of an expression then the prefix and postfix forms
would produce entirely different results.
In the prefix form, the operand is incremented or decremented before the operand is used in
the program. Whereas in the postfix form, the operand is used first and then incremented or decre-
mented.

1.9.2 Relational and logical Operators


A relational operator is used to compare two values and the result of such an operation is always logical,
i.e., either true or false. The valid relational operators supported by C are given in Table 1.4.
Overview of C 15

n Table 1.4 Relational operators supported by C


Symbol Stands for Example
. greater than x.y
.5 greater than equal to x.5y
, less than x,y
,5 less than equal to x ,5 y
55 equal to x55y
!5 not equal to x!5y

Example 2: Take two variables x and y with initial values 10 and 15, respectively. Demonstrate the usage
of relational operators by using x and y as operands.
Solution: The usage of relational operators is illustrated below with the help of a table:
x = 10, y = 15

Expression Result
x.y False
x 1 5> 5 y True
x<y True
x<5y True
x55y False
x 1 555y True
x! 5 y True

A logical operator is used to connect two relational expressions or logical expressions. The result of
such an operation is always logical, i.e., either true or false. The valid logical operators supported by C
are given in Table 1.5.

n Table 1.5 Logical operators supported by C


Symbol Stands for Example
&& Logical AND x&&y
|| Logical OR x||y
! Logical NOT !x

Rules of logical operators:


(1) The output of a logical AND operation is true if both of its operands are true. For all other
combinations, the result is false.
(2) The output of logical OR operation is false if both of its operands are false. For all other
combinations, the result is true.
(3) The logical NOT is a unary operator. It negates the value of the operand.
16 Data Structures Using C

For initial value of x 5 5 and y 5 7, consider the following expression:


(x , 6) && (y . 6)
The operand x , 6 is true and the operand y . 6 is also true. Thus, the result of above given logical
expression is also true. However, the result of following expression is false because one of the operands
is false:
(x , 6) && (y . 7)
Similarly, consider the following expression:
(x , 6) || (y . 7)
The operand x , 6 is true whereas the operand y . 7 is false. Since these operands are connected by
logical OR, the result of this expression is true (Rule 2). However, the result of the following expression
becomes false because both the operands are false.
!(x , 6) || (y . 7)
Note: The expression on the right hand side of logical operators && and || does not get evaluated in case
the left hand side determines the outcome.
Consider the expression given below:
x && y

If x evaluates to false (zero), then the outcome of the above expression is bound to be false irrespec-
tive of y evaluating to any logical value. Therefore, there is no need to evaluate the term y in the above
expression.
Similarly, in the following expression, if x evaluates to true (non zero) then the outcome is bound to
be true. Thus, y will not be evaluated.
x || y

1.9.3 Conditional Operator


C provides a conditional operator (? :) which can help the programmers in performing simple
conditional operations. It is represented by the symbols ‘?’ and ‘:’. For example, if one desires to assign
the bigger of the two variables x and y to a third variable z the conditional operator is an excellent tool.
The general form of this operation is:
E1?E2:E3
where E1, E2, and E3 are expressions.
In the conditional operation, the expression E1 is tested, if E1 is true then E2 is evaluated otherwise
the expression E3 is evaluated as shown in Figure 1.4.
Consider the following conditional expression:
z = (x > y)? x : y;

The expression x > y is evaluated. If x is greater than y, then z is assigned x otherwise z gets y.
Examples of valid conditional expressions are:
(i)
y 5 (x . 5 10)?0:10;
Overview of C 17

true

E1 ? E2 : E3

false

Fig. 1.4 The conditional operator

(ii)
Res 5 (i < j)? sum 1 i : sum 1 j;
(iii)
q 5 (a 5 5 0)?0:(x/y);
It may be noted here that the conditional operator (? :) is also known as a ternary operator because
it operates on three values.

1.9.4 Order of Evaluation of Expressions


A number of logical and relational expressions can be linked together with the help of logical operators
as shown below:
(x , y) || (x . 20) && !(z) || ((x , y) && (z . 5))
For a complex expression such as given above, it becomes difficult to make out as to in what order
the evaluation of sub-expressions would take place.
In C, the order of evaluation of an expression is carried out according to the operator precedence
given in Table 1.6.

n Table 1.6 Operator precedence


Operators priority associativity
− 11 −− ! Highest Right to left
*/% Left to right
1− Left to right
< <5 > >5 Left to right
55 !5 Left to right
&& Left to right
|| Lowest Left to right

It may be noted here that in C, false is represented as zero and true as any non-zero value. Thus,
expressions that use relational and logical operators return either 0 (false) or 1 (true).
18 Data Structures Using C

1.9.5 Some Special Operators


There are many other operators in C. In this section, the two frequently used operators—sizeof and
comma operators—have been discussed.
1. Sizeof operator: C provides a compile time unary operator called sizeof which, when applied
on an operand, returns the number of bytes the operand occupies in the main memory. The
operand could be a variable, a constant or a data type. For example, the following expressions:
a 5 sizeof (“sum”);
b 5 sizeof (char);
c 5 sizeof (123L);
would return the sizes occupied by variables sum, data type char and constant ‘123L’ on your machine.
It may be noted that
n the parentheses used with sizeof are required when the operand is a data type with variables or

constants, the parentheses are not necessary.


n sizeof operator has the same precedence as prefix increment/decrement operators.

2. Comma operator: The comma operator is used to string together a number of expressions
which are performed in a sequence from left to right.
For example, the following statement
a 5 (x 5 5, x 1 2)
executes in the following order
(i) value 5 is assigned to variable x.
(ii) x is incremented by 2.
(iii) the value of expression x 1 2 (i.e., 7) is assigned to the variable a.
The following points may be noted regarding comma operator:
n A list of expressions separated by a comma is always evaluated from left to right.

n The final value and type of a list of expressions separated by a comma is always same as the type

and value of the rightmost expression in the list.


n The comma operator has the lowest precedence among all C operator.

1.9.6 assignment Operator


Statements are the smallest executable units of a C program and each statement is terminated with a
semicolon. An assignment statement assigns the value of the expression on the right hand side to a vari-
able on the left hand side of the assignment operator (=). Its general form is given below:
<variable name> = <expression>

The expression on the right hand side could be a constant, a variable or an arithmetic, relational, or
logical expression. Some examples of assignment statements are given below:
a 5 10;
a 5 b;
a 5 b*c;

(i) The assignment operator is a kind of a store statement, i.e., the value of the expression on the
right hand side is stored in the variable appearing on the left side of the assignment operator.
Overview of C 19

The variable on the left side of the assignment operator is also called lvalue and is an accessible
address in the memory. Expressions and constants on the right side of the assignment operator
are called rvalues.
(ii) The assignment statement overwrites the original value contained in the variable on the left
hand side with the new value of the right hand side.
(iii) Also, the same variable name can appear on both sides of the assignment operator as shown
below:

count 5 count 11;

(iv) Multiple assignments in a single statement can be used, especially when same value is to be
assigned to a number of variables.

a 5 b 5 c 5 30;

These multiple assignment statements work from right to left and at the end, all variables have the
same value. The above statement assigns the value (i.e., 30) to all variables c, b, and a. However, the
variables must be of same type.
(v) A point worth nothing is that C converts the type of value on the right hand side to the data
type on the left.

1.9.7 Bitwise Shift Operators


C supports special bitwise shift operators: shift left (<<) and shift right (>>). We know that data
at machine level is represented in the binary form and it can be shifted to left or right by these special
operators. However, the number of bits to be shifted is specified by an integer written next to the opera-
toras shown below:
x << 3;
The above statement means that the value contained in x is shifted to left by 3 bits. Thus, the leftmost
3 bits of x will be lost and the resultant vacant 3 rightmost bits will be filled by zeros as shown in
Figure 1.5.
x (before left shift)

0 1 0 1 1 1 0 1




Lost bits

x (after left shift)

1 1 1 0 1 0 0 0




Appended zero bits

Fig. 1.5 The contents of x before and after left shift


20 Data Structures Using C

Similarly, the following expression would shift the contents of y to right by two bits:
y >> 2

In this case, the rightmost two bits would be lost and the resultant 2 vacant leftmost bits would be
filled by zeros as shown in Figure 1.6.

y (before right shift)

1 1 0 1 1 0 1 1


Lost bits

y (after right shift)

0 0 1 1 0 1 1 0


Appended zero bits

Fig. 1.6 The contents of y before and after right shift

1.10 FlOW OF COnTROl


A statement is the smallest executable unit of a C program. It is terminated with a semicolon. It is an
instruction given to the computer to perform a particular task like reading input, displaying output or
evaluating an expression, etc.
A single statement is also called a simple statement. Some examples of simple statement are given
below:
(i) int a 5 100;
(ii) S 5 S 1 a;
(iii) count 11;
A statement can also be an empty or null statement as shown below:
;

The high level languages are designed for computers based on Von-Neumann architecture. Since this
architecture supports only sequential processing, the normal flow of execution of statements in a high
level language program is also sequential, i.e., each statement is executed in the order of its appearance
in the program. For example in the following C program segment, the order of execution is sequential
from top to bottom.
:
x 5 10;
y 5 20; Order of execution
z 5 x 1 y;
:
Overview of C 21

The first statement to be executed is ‘x 5 10’, and the second statement to be executed is ‘y 5
20’. The execution of statement ‘z 5 x 1 y’ will take place only after the execution of the statement
‘y 5 20’. Thus, the processing is strictly sequential. Moreover, every statement is executed once and
only once.
Depending upon the requirements of a problem, it is often required to alter the normal sequence
of execution in the program. This means that we may desire to selectively and/or repetitively execute a
program segment. A number of C control structures are available for controlling the flow of processing.
These structures are discussed in the following sections.

1.10.1 The Compound Statement


A compound statement is a group of statements separated from each other by a semicolon. The group
of statements, also called a block of code, is enclosed between a pair of curly braces, i.e., ‘{‘ and `}’.
The significance of a block is that the sequence of statements enclosed in it is treated as a single unit. For
example, the following group of statements is a block.
/* a block of code*/
{
scanf (“%d %d”, & a, & b);
c = a + b;
printf (“\n %d”, c);
}

One compound statement can be embedded in another as shown below:


{
:
{
:
}
:
}

In fact, the function of curly braces ‘{‘ and `}’ in a C program to create a block, is same as the
function of begin and end, the reserved words in Pascal. C calls these braces as delimiters.

1.10.2 Selective Execution (Conditional Statements)


In some cases, it is desired that a selected segment of a program be executed on the basis of a test, i.e.,
depending upon the state of a particular condition being true or false. In C, ‘if statement’ is used for
selective execution of a program segment.
(1) The if statement: This statement helps us in the selection of one out of two alternative courses
of action. The general form of ‘if statement’ is given below:
if (expression)
{
statement sequence
}

where if: is a reserved word.


22 Data Structures Using C

is a boolean expression enclosed within a set of parentheses (These paren-


expression:
theses are necessary even if there is a single variable in the expression).
statement sequence: is either a simple statement or a block. However, it cannot be a declaration.

Examples of acceptable ‘if statements’ are:


(i) if (A > B) A = B;
(ii) if (total < 100) {
total = total + val;
count = count + 1;
}
(iii) if ((Net > 7000) && (l_tex == 500)) {
:
}

(2) The if-else statement: It can be observed from the above examples that the simple if statement
does nothing when the expression is false. An if-else statement takes care of this aspect. The
general form of this construct is given below:
if (expression)
{
statement sequence1
}
else
{
statement sequence2
}
where if: is a reserved word.
expression: is a boolean expression, written within parentheses.
statement sequence1: can be a simple or a compound statement.
else: is a reserved word.
statement sequence2: can be a simple or a compound statement.
Examples of if-else statements are:
(i) if (A > B) C = A;
else C 5 B;
(ii) if (x == 100)
printf (“\n Equal to 100”);
else
printf (“\n Not Equal to 100”);
It may be noted here that both the ‘if ’ and ‘else’ parts are terminated by semicolons.
(3) Nested if statements (if-else-if ladder): The statement sequence of if or else may contain an-
other if statement, i.e., the if-else statements can be nested within one another as shown below:
if (exp1)
if (exp2)
{
Overview of C 23
:
}
else
if (exp3)
{
:
}
else
{
:
}

It may be noted here that sometimes the nesting may become complex in the sense that it becomes
difficult to decide “which if does the else match”. This is called “dangling else problem’’. The C
compiler follows the following rule in this regard:
Rule: Each else matches to its nearest unmatched preceding if.
Consider the following nested if:
if (x < 50) if (y > 5) Net = x + y; else Net = x – y;

In the above statement, the else part matches the second if (i.e., if (y . 5)) because it is the nearest
preceding if. It is suggested that the nested if(s) should be written with proper indentation. The else(s)
should be lined up with their matching if(s). Nested if(s) written in this fashion are also called if-else-if
ladder. For example, the nested if given above should be written as:
if (x < 50)
if (y > 5)
Net = x + y;
else
Net = x – y;
However, if one desires to match the else with the first if, then the braces should be used as shown
below:
if (x < 50) {
if (y > 5)
Net = x + y;
}
else
Net = x – y;
The evaluation of if-else-if ladder is carried out from top to bottom. Each conditional expression
is tested and if found true, only then its corresponding statement is executed. The remaining ladder is,
therefore, by passed. In a situation where none of the nested conditions is found true, the final else part
is executed.
(4) Switch statement (selection of one of many alternatives): If it is required in a program to
select one of several different courses of action, then the switch statement of C can be used. In
fact, it is a multibranch selection statement that makes the control to jump to one of the several
statements based on the value of an int variable or expression. The general form of this state-
ment is given as:
24 Data Structures Using C
switch (expression)
{
case constant 1:
statement;
break;
case constant 2:
statement;
break;
:
default:
statement;
}

where switch: is a reserved word.


expression: it must evaluate to an integer or character value.
case: is a reserved word.
constant: it must be an int or char compatible value.
statement: a simple or compound statement.
default: is a reserved word and is an optional entry.
break: is a reserved word that stops the execution within the switch and control
comes out of the switch construct.
The switch statement works according to the following rules:
n The value of the expression is matched with the random case constants of the switch construct.

n If a match is found then its corresponding statements are executed and when break is encountered,

the flow of control jumps out of the switch statement. If break statement is not encountered, then
the control continues across other statement. In fact, switch is the only statement in C which is error
prone. The reason is that if the control is in a particular case and then it keeps running through all
cases in the absence of a proper break statement. This phenomenon is called “fall-through”.
n If no match is found and if a default label is present, then the statement corresponding to default

is executed.
n The values of the various case constants must be unique.

n There can be only one default statement in a switch statement.

Examples of acceptable switch statements are:


(i)
switch (BP)
{
case 1 : total + = 100;
break;
case 2 : total + = 150;
break;
case 3 : total + = 250;
}

(ii)
switch (code)
Overview of C 25
{
case 101 : Rate = 50; break;
case 102 : Rate = 70; break;
case 103 : Rate = 100; break;
default : Rate = 95;
}

In the statement (ii), it can be observed that depending on the value of the code one out of the four
instructions is selected and obeyed. For example, if the code evaluates to 103, the third instruction (i.e.,
Rate 5100) is selected. Similarly if the code evaluates to 101, then the first instruction (i.e., Rate 5 50) is
selected.

1.10.3 Repetitive Execution (Iterative Statements)


Some problems require a set of statements to be executed a number of times, each time changing the
values of one or more variables so that every new execution is different from the previous one. This kind
of repetitive execution of a set of statements in a program is known as a loop.
We can categorize loop structures into two categories: non-deterministic loops and deterministic
loops. When the number of times the loop is to be executed is not known, then the loop is called non-
deterministic loop otherwise it is called a deterministic loop.
C supports while, do while, and for loop constructs to help repetitive execution of a compound
statement in a program. The ‘while’ and ‘do while’ loops are non-deterministic loops and the `for’ loop
is a deterministic loop.
1. The while loop: It is the fundamental conditional repetitive control structure in C. The general
form of this construct is given below:
while <cond> statement;

where while: is a reserved word of C.


<cond>: is a boolean expression.
statement: can be a simple or compound statement.

The sequence of operation in a while loop is as follows:


(1) Test the condition.
(2) If the condition is true, then execute the statement and repeat step 1.
(3) If the condition is false, leave the loop and go on with the rest of the program.
It may be noted here that the variables used in the <cond> or boolean expression must be initialized
somewhere before the while statement is encountered. It is a pre-test loop in the sense that the condition
is tested before the body of the loop is executed.
2. The do-while loop: It is another conditional repetitive control structure provided by C. The
syntax of this construct is given below:
do
{
statement;
}
while <cond>;
26 Data Structures Using C

where do: is a reserved word.


statement: can be a simple or a compound statement.
while: is a reserved word.
<cond>: is a boolean expression.
The sequence of operations in a do-while loop is as follows:
(1) Execute the statement.
(2) Test the condition.
(3) If the condition is true, then repeat steps 1 to 2.
(4) If the condition is false, leave the loop and go on with the rest of the program.
Thus, it performs a post-test in the sense that the condition is not tested until the body of the loop
is executed at least once.
3. The for loop: It is a count controlled loop in the sense that the program knows in advance as to
how many times the loop is to be executed. The general form of this construct is given below:
for (initialization; expression; increment)
{
statement
}

where for: is a reserved word.


initialization: is usually an assignment expression wherein a loop control variable is initialized.
expression: is a conditional expression required to determine whether the loop should
continue or be terminated
increment: it modifies the value of the loop control variable by a certain amount.
statement: can be a simple or a compound statement.
The loop is executed with the loop control variable at initial value, final value and the values in
between.
We can increase the power of for-loop with the help of the comma operator. This operator allows the
inclusion of more than one expression in place of a single expression in the ‘for’ statement as shown below:
for (exp1a, exp1b; exp2; exp3a, exp3b;) statement;
Consider the following program segment:
:
for (i = 1, j = 10; i < = 10; i++, j--)
{
:
}

The variable i and j have been initialized to values 1 and 10, respectively. Please note that these
initialization expressions are separated by a `comma’. However, the required semicolon remains
as such. During the execution of the loop, i increases from 1 to 10 whereas j decreases from 10 to 1
simultaneously. Similarly, the increment and decrement operations have been separated by a `comma’
in the ‘for statement’.
Though the power of the loop can be increased by including more than one initialization and
increment expression separated with the comma operator but there can be only one test expression
which can be simple or complex.
Overview of C 27

1.10.3.1 The ‘break’ and ‘continue’ Statements The break statement can be used in any ‘C᾽ loop
to terminate execution of the loop. We have already seen that it is used to exit from a switch statement. In
fact, whenever the break statement is encountered in a loop the control is transferred out of the loop. This
is used in a situation where some error is found in the program inside the loop or it becomes unnecessary
to continue with the rest of the execution of the loop.
Consider the following program segment:
:
while (val != 0)
{
:
printf (“\n %d”, val);
if (val < 0) {
printf (“\n Error in input”);
break;
}
:
}

Whenever the value contained, in variable val becomes negative, the message `Error in input’
would be displayed and because of the break statement the loop will be terminated.
The continue statement can also be used in any ‘C᾽ loop to bypass the rest of the code segment of
the current iteration of the loop. The loop, however, is not terminated. Thus, the execution of the loop
resumes with the next iteration. For example, the following loop computes the sum of positive numbers
in a list of 50 numbers:
:
sum = 0;
for (i = 0; i < 50; i ++)
{
printf (“\n %d”, val);
if (val <= 0) continue;
sum = sum + val;
}
:

It may be noted here that continue statement has no relevance as far as the switch statement is con-
cerned. Therefore, it cannot be used in a switch statement.

1.10.4 The exit() Function


In the event of encountering a fatal error, the programmer may desire to terminate the program itself. For such
a situation, ‘C᾽ supports a function called exit() which can be invoked by the programmer to exit from the
program. This function can be called from anywhere inside the body of the program. For normal termination,
the programmer can include an argument ‘0’ while invoking this library function as shown below:
#include <stdio.h>
#include <process.h>
void main()
28 Data Structures Using C
{
:
if (error) exit (0);
:
}

It may be noted here that the file process.h has to be included as header file because it contains the
function prototype of the library function exit().

1.10.5 nested loops


It is possible to nest one loop construct inside the body of another. The inner and outer loops need not
be of the same construct as shown below.
while <cond>
{
do
{
} while <cond>;
for (init; exp; inc)
{
:
}
:
}
The rules for the formation of nested loops are:
(1) An outer for loop and an inner for loop cannot have the same control variable.
(2) The inner loop must be completely nested inside the body of the outer loop.

1.10.6 The Goto Statement (unconditional Branching)


The unconditional transfer of control means that the sequence of execution will be broken without
performing any test and the control will be transferred to some statement other than the immediate next
one. C supports the following statement for this purpose.
goto <statement label>

where goto: is a reserved word.


<statement label>: is an identifier used to label the target statement.
The goto statement causes control to be transferred to the statement whose label is specified in the
goto statement. Consider the following program segment:

-
-
goto rpara;
-
-
rpara: -
-
-
Overview of C 29

The goto statement will cause the control to be transferred to a statement whose label is rpara. The
normal flow of execution will continue from this statement (i.e., having label rpara) onwards. Consider
the following program segment:
:
k = 50;
back: I++
:
sum = sum + k*I ;
k--;
goto back;
:

It is clear from the above segment that as and when the control reaches the goto statement, it is
transferred to the statement with label back.

Statement label A statement label is an identifier which can be placed before any C statement followed
by a colon (i.e., :) as shown below:
again: C 5 A 1 B;
Thus, again is a label attached to the statement C 5 A 1 B and the control of execution can be
transferred to this statement by the following goto statement.
goto again;
It may be noted here that the transfer of control out of a control structure is allowed. However, a goto
branch into a control structure is not allowed.
Some example programs using control structures are given below.
Example 3: Write a program that reads three numbers and prints the largest of them.
Solution: The if-else ladder would be used. The required program is given below:
/* This program displays the largest of three numbers */
#include <stdio.h>
main()
{
int A, B, C;
printf (“\n Enter the Numbers A, B, C:“);
scanf (“%d %d %d”, &A, &B, &C);
/* if-else ladder */

if (A > B)
if ( A > C)
printf (“\n A is largest”);
else
printf (“\n C is largest”);
else
if (B > C)
printf (“\n B is largest”);
else
30 Data Structures Using C
printf (“\n C is largest”);
/* end of ladder */
}

Example 4: Write a program that prints all perfect numbers between 2 and 9999, inclusive. A perfect
number is a positive integer such that the number is equal to the sum of its proper divisors. A proper
divisor is any divisor whose value is less than the number.

Solution: The remainder operator ‘%’ would be used to find whether a number is divisor of an-
other or not. The maximum value of perfect divisor cannot be more than the half the value of the
number.
The required program is given below:
/* This program finds out all the perfect numbers between 2 and 9999 both
inclusive */
#include <stdio.h>
main()
{
int num, divisor;
int sum;
char ch;

for (num = 2; num , = 9999; num++)


{
sum = 1; /* 1 is proper divisor of all positive integers */

for (divisor = 2; divisor < = num/2; divisor++)


{
if (num % divisor 55 0)
sum 5 sum 1 divisor;
}
if ( sum 55 num )
printf (“\n %d is a perfect number”, num);
}
}

1.11 InpuT–OuTpuT FunCTIOnS (I/O)


Most of the programs read and write data through input/output devices such as screen, keyboard,
printer, and disk devices, etc. Obviously, the programmer has to learn how to perform correct I/O
operations so that efficient programs can be written. We have already used two C functions printf()
and scanf() in the previous examples. In the following sections, we will discuss some of the follow-
ing input output functions:
Function Type Description
(1) getchar() stream reads a character from a stream
(2) putchar() stream writes a character to the stream
Overview of C 31

(3) getc() stream reads a character from a stream


(4) putc() stream writes a character to a stream
(5) gets() stream reads a string from a stream
(6) puts() stream writes a string to a stream
(7) cgets() console reads a string from system consol
(8) getche() console reads a character from system consol
(9) putch() console writes a character on system consol
(10) cputs() console writes a string on system consol

In order to use the above functions, the programmer must include the ‘stdio.h᾽ header file at the
beginning of his program. The C or ‘C environment’ assumes keyboard as the standard input device and
VDU as standard output device. A consol comprises both keyboard and VDU.
By default, all stream I/Os are buffered. At this point, it is better that we understand the term buff-
ered I/O before we proceed to discuss the stream I/O functions.

1.11.1 Buffered I/O


Whenever we read from the keyboard or from a file stored on a device, a block of data is stored in a buf-
fer called input buffer. The input stream, therefore, reads from the buffer with the help of a pointer until
the input buffer is empty (see Figure 1.7). As soon as the buffer becomes empty, the next block of data is
transferred into the buffer from the I/O device.

Block of data Data

Input buffer

Stream

I/O devices

Block of data Data

Outbut buffer

Fig. 1.7 Buffered I/O

Similarly, data written by an output stream pointer is not directly written onto the device but into an
output buffer. As soon as the output buffer becomes full, a block of data is written on to the I/O device
making output buffer empty.
32 Data Structures Using C

When the header file stdio.h is included in a program, the following standard stream pointers are
automatically opened:

name Meaning
stdin standard input
stdout standard output
stderr standard error
stdaux auxiliary storage
stdprn printer

In the computer, ‘stdin’ and ‘stdout’ refer to the user’s console, i.e., input device as keyboard
and output device as VDU (screen). The stream pointers ‘stdprn’ and ‘stdaux’ refer to the printer and
auxiliary storage, respectively. The error messages generated by the stream are sent to standard error
(stderr).
In order to clear the buffers, a function called ‘fflush()’ can be used. For example, input buffer of
standard input device can be cleared by invoking the function: ‘fflush(stdin)’.

1.11.2 Single Character Functions


C supports many input and output functions based on character. These functions read or write one
character at a time. C supports both stream and consol I/O character-based functions. We will discuss
them in the following sections.
(1) getchar() and putchar() Functions: The getchar() function reads a single character
from the standard input device. For example, if it is desired to read a character from keyboard
in a character variable ch then the following statements can be used:
:
char ch;
ch = getchar();
:

Since the function getchar() is a stream I/O function, it is buffered in the sense that the character
typed by the user is not passed to the variable ch until the user hits the enter or return key, i.e., ↵. The
enter key is itself a character and it also gets stored in the buffer along with the character typed by the
user. The entry of `enter key’ character into the buffer creates problems in the normal functioning of
getchar() function. Therefore, it is suggested that after an input operation from the standard input
device (i.e., keyboard) the input buffer should be cleared. This operation is required to avoid interference
with subsequent input operations. The function call for this activity is: fflush (stdin). The usage is
shown below:
:
char ch;
ch = getchar();
fflush (stdin);
:
Overview of C 33

The function putchar() is used to send a single character to the standard output device. The character
to be displayed on the VDU screen is included as an argument to the putchar() function as shown below:
:
ch = `A’;
putchar (ch);
:

Once the above program segment is executed, the character ‘A’ will be displayed on the screen.
The putchar() function is also buffered. The function call for clearing the output buffer is fflush
(stdout). The output buffer is cleared on its own only when a new line character `\n’ is used.
(2) getc() and putc() Functions: The getc() and putc() functions are also character-
based functions. They have been basically designed to work with files. However, these
functions can also be used to read and write data from standard input and output devices by
specifying stdin and stdout as input and output files, respectively.
For example, the function getc(stdin) is equivalent to the function getchar(). Both will get a
character from the standard input device (keyboard). The function getchar() by default reads from
keyboard whereas the argument stdin of function getc(stdin) makes it read from a file represented
by the standard input device which is nothing but the keyboard.
Similarly, the function putc(ch, stdout) is equivalent to the function putchar(ch). Both the
functions send the character ch to the standard output device, i.e., VDU screen.
(3) getche() and putch() Functions: These two functions are character-based versions of con-
sole I/O functions. Therefore, the header file conio.h has to be included. In fact, these functions
act as an extension to the stream I/O functions. The console I/O functions read from the key-
board and write to the screen directly.
n getche(): This function directly reads a character from the console as soon as it is typed

without waiting for the enter key (↵) to be pressed. There is another similar function getch()
which also reads a character from the keyboard exactly in the same manner but does not show
it on the screen. This function is useful in menu selections where the programmer does not
want to display the character typed by the user. In fact, the extra ‘e’ in the getche() function
stands for echo, i.e., display the character.
Examples of usage of these functions are:
(i) ch 5 getche();
(ii) ch 5 getch();
n putch(): This function directly writes a character on the console. It takes character as an
argument.
Examples of usage of this function are:
(i) putch (‘\n’); //It takes the cursor to next line of the screen.
(ii) putch (ch); //It displays the character stored in the variable ch on the screen.
(iii) putch (‘A’); //It displays the character ‘A’ on the screen.
Note: These functions cannot read special keys from the keyboard such as function keys.

1.11.3 String-based Functions


String-based functions read or write a string of characters at a time. C supports both stream and console
I/O string-based functions.
Exploring the Variety of Random
Documents with Different Content
The text on this page is estimated to be only 22.83%
accurate

HE [E ONE
The text on this page is estimated to be only 28.73%
accurate

THE VICTORIA HISTORY OF THE COUNTY OF ESSEX


VOLUME ONE WESTMINSTER 2 WHITEHALL GARDENS 1903
The text on this page is estimated to be only 26.33%
accurate

DA v, !
The text on this page is estimated to be only 27.86%
accurate

Counts Committee for Eeaey THE RT. HON. THE EARL OF


WARWICK Lord Lieutenant^ Chairman THE RT. HON. THK LORD
CLAUD J. HAMILTON THE RT. REV. THE LORD BISHOP OF ST.
ALBANS THE RT. HON. THE LORD RAYLEIGH THE RT. HON. THE
LORD HAWKESBURY THE RT. HON. SIR JOSEPH C. DIMSDALE,
BART., M.P. THE RT. HON. JAMES ROUND, M.P. THE HON. CHARLES
HEDLEY STRUTT, M.P. SIR THOMAS L. H. NEAVE, BART. SIR WALTER
GILBEY, BART. SIR JAMES BLYTH, BART. SIR EDMUND DU CANE,
K.C.B. ADMIRAL SIR WILLIAM G. LUARD, K.C.B. SIR H. SEYMOUR
KING, K.C.I.E., M.P. THE RT. REV. THE BISHOP OF COLCHESTER THE
RT. REV. THE BISHOP OF BARKING THE WORSHIPFUL THE MAYOR
OF CHELMSFORD THE WORSHIPFUL THE MAYOR OF COLCHESTER
THE WORSHIPFUL THE MAYOR OF HARWICH THE WORSHIPFUL
THE MAYOR OF MALDON COL. GEORGE BRAMSTON ARCHER-
HOUBLON, J-P. JAMES BAILEY, ESQ., M.P., J.P. THOMAS BARRETT-
LENNARD, Esq.,J.P.,D.L. THE REV. R. E. BARTLETT, M.A. G. F.
BEAUMONT, ESQ., F.S.A. CHARLES E. BENHAM, ESQ. W. GURNEY
BENHAM, ESQ., J.P. G. S. BOULGER, ESQ., F.L.S., F.G.S. E. N.
BUXTON, ESQ. FREDERIC CHANCELLOR, ESQ., F.R.I. B.A. MILLER
CHRISTY, ESQ., F.L.S. R. BEALE COLVIN, ESQ., J.P., D.L. GEORGE
COURTAULD, ESQ., J.P. THE REV. CECIL DEEDES, M.A. CLAUDE E.
EGERTON-GREEN, ESQ., M.A., J.P., D.L. E. A. FITCH, ESQ., F.L.S.,
F.E.S. JOHN LEWIS FFYTCHE, ESQ., F.S.A., J.P., D.L. THE REV. F. W.
GALPIN, M.A., F.L.S. A. R. GODDARD, ESQ. I. C. GOULD, ESQ.
HORACE G. EGERTON GREEN, ESQ., J.P., D.L. HUGH E. HOARE, ESQ.
THOMAS VINCENT HOLMES, ESQ., F.G.S., M.A.I. DAVID HOWARD,
ESQ., D.L. ELIOT HOWARD, ESQ., J.P., D.L. HENRY JOSLIN, ESQ.,
J.P., D.L. COMMANDER KELSO, R.N., J.P., D.L. THE REV. J. W.
KENWORTHY FRANK LANDON, ESQ. HENRY LAVER, ESQ., F.S.A.,
F.L.S. COL. A. R. M. LOCKWOOD, M.P., J.P. GEORGE ALAN
LOWNDES, ESQ., J.P., D.L. JAMES H. A. MAJENDIE, ESQ., M.P., J.P.,
D.L. WILSON MARRIAGE, ESQ., J.P. R. MELDOLA, ESQ., F.R.S.,
F.R.A.S., F.C.S. MAJOR F. L. NATHAN, R.A. W. NOCTON, ESQ., J.P.
THE REV. CANON C. F. NORMAN, M.A., J.P. CHRISTOPHER W.
PARKER, ESQ., J.P., D.L. JAMES N. PAXMAN, ESQ., J.P. J. TIMBRELL
PIERCE, ESQ., F.R.G.S., J.P., D.L. THE REV. LEWIS N. PRANCE, M.A.
J. HORACE ROUND, ESQ., D.L. A. W. RUGGLES-BRISE, ESQ., J.P.,
D.L. J. C. SHENSTONE, ESQ., F.L.S. CHARLES BROGDEN SPERLING,
ESQ., J.P., D.L. C. F. D. SPERLING, ESQ., J.P. COL. NEVILL TUFNELL,
J.P., D.L. COL. J. L. TUFNELL-TYRELL, J.P., D.L. W. CHAPMAN
WALLER, ESQ., F.S.A. JAMES F. T. WISEMAN, ESQ. xiii
The text on this page is estimated to be only 26.18%
accurate

CONTENTS OF VOLUME ONE Dedication ....... The Advisory


Council of the Victoria History . General Advertisement . . . . . The
Essex County Committee . Contents ....... List of Illustrations . . . . . .
. Preface Natural History Geology .... Palaeontology Botany ....
Zoology Marine Mollusca (Snath, etc.) Insecta (Insects) Myriapoda
(CentifeJei) . . Arachnida (Spiders) . . . Crustacea (Crabs, etc.) . ,
Pisces (Fishes) , Reptilia (Reptiles) and Batrachia (Batrachiani) . ,
Aves (BitJi) . Mammalia (Mammals) . . Early Man Ancient Earthworks
. , Anglo-Saxon Remains Introduction to the Essex Domesday Text of
the Essex Domesday Index to the Essex Domesday . , PAGE V VII vii
xiii XV xvii xix By H. B. WOODWARD, F.G.S. By RICHARD LYDEKKER,
B.A., F.R.S., F.G.S. By J. C. SHENSTONE, F.L.S. . By WALTER
GARSTANC, assisted by H. C. SORBY, LL.D., F.R.S., F.S.A. . . . By B.
B. WOODWARD, F.G.S., F.R.M.S. . . By W. HARWOOD . . . . . ' By R.
I. POCOCK . . . . . . By F. O. PICKARD-CAMBRIDCE, M.A. . . . By the
Rev. T. R. R. STEBBINC, M.A., F.R.S., F.S.A., F.L.S ..... . . By H.
LAVER, J.P., F.S.A., F.L.S., M.R.C.S. . ,, „ . . By MILLER CHRISTY, F.L.S
...... By H. LAVER, J.P., F.S.A., F.L.S., M.R.C.S. . By GEO. F.
BEAUMONT, F.S.A., and I. CHALKLEY GOULD . . . . . . . . By I.
CHALKLEY GOULD ..... By REGINALD A. SMITH, B.A ..... By J.
HORACE ROUND, M.A. . . . 3" 69 89 9' 193 196 204 220 230 232
254 261 275 315 333 4*7 $79 xv
The text on this page is estimated to be only 24.60%
accurate

LIST OF ILLUSTRATIONS PAC« Canvey Island. By WILLIAM


HYDE fhatiifieee Palaeolithic Weapons from the Lea Valley \ full-pafe
flatr, fadne 262 Neolithic Celts from Inworth and Stisted j Weapons
from Walton, Shoebury, Dovercourt, near Stansgate and Colchester
.......... „ „ „ 264 Pottery from Chcsterford, Great Clacton, Great
Oakley and Colchester „ „ „ 265 Pcnannular Armlet and Palstave from
Shoebury ..... • 266 Palstaves from Shoebury and Pleshcy . . .} . full-
Met plate, faang 266 Bronze Socketed Celts from Hatfield Broad Oak
J Bronze Spearheads from Plaistow Marshes, Walthamstow, and
Hatfield Broad Oak „ „ „ 267 Handles of a Bronze Cauldron from
Hatfield Broad Oak . Part of the Box of a Chariot Wheel, with Nails,
found at Shoebury „ „ „ 268 Parts of the Rim of a large Vessel from
Hatfield Broad Oak Late Celtic Vessels, etc „ „ » 269 Implements
from Site of Fascine Dwellings 270 View of the Site of Fascine
Dwellings at Braintrcc Loughton Camp .......... 277 Ambresbury
Banks .......... Ring Hill Camp, Littlebury ..... 280 Uphall
Entrenchments, near Barking .... .281 Wallbury Camp *8* Pitchbury
Ramparts, Great Horkesley .... Shoeburyness .......... Witham Bury
.288 Bcrden Mound ........... • *89 Great Canfield • *9° Covering
.292 Great Easton .293 Mound in Castle Grove, Elmdon • *94
Hedingham Castle • 294 Ongar Castle • *97 Pleshey • 298 Rayleigh
Mount Rickling 3°" Stansted . . 3°' xvii
The text on this page is estimated to be only 23.78%
accurate

LIST OF ILLUSTRATIONS Stebbing Mount ....... Sections of


a Denehole and Ground Plan of Chambers Anglo-Saxon Objects ......
Bronze Pan from Broomfield ..... Iron Standing-Cup ....... Pottery
Vase ....... Turold Milking Ewes Wallasea Island Canvey Island PAGE .
3°z • 3°9 coloured plate facing 322 . 3" • 323 • 3H full-page plate
facing 342 » » » 369 LIST OF MAPS Geological Map Botanical Map
Pre-Historical Map. Earthworks Map Anglo-Saxon Map . Domesday
Map between xxii, I 30, 31 260, 261 274. 275 3H» 315 426, 427
XVlll
The text on this page is estimated to be only 28.58%
accurate

PREFACE I only complete history of Essex hitherto issued is


that of Philip Morant, published in 1768 and reprinted in i8i6.1 It
may perhaps be reasonably claimed that the county is entitled to a
newer history and one more complete than could be compiled in the
eighteenth century. The aims of the series of which the Victoria
History of Essex forms a part are to be found in the General
Advertisement printed in this volume. It has been found impossible
in the present instance to adhere to chronological order in the
sequence of the articles included in this volume. It is hoped to print
the section on the Romano-British Period in the second volume.
Whilst the editors cannot as a rule make special reference to the
services of contributors, they feel in the present instance it is only
right to acknowledge their great indebtedness to Mr. J. Horace
Round, not only for the infinite pains he has expended under
adverse circumstances of health on the Domesday section, which in
the case of Essex is one of peculiar difficulty, but also for the
valuable help he has given to others in the preparation and revision
of their articles. * It would appear that Morant did little more than
edit materials collected by previous students of Essex history (see
'Historians of Essex,' Enex Review, iii. 27-41, 138-53). XIX
The text on this page is estimated to be only 29.50%
accurate

A HISTORY OF ESSEX
The text on this page is estimated to be only 8.93%
accurate

TH STORY OF ESSEX GEOLOC ff VEX !• v »W-»..«• n,.,,.,,,,


,:,!,: '-•- , • ,^#? '^^m^^kA*'"^' fU*'A-' ^7- baVroRD^ TV.
Eouilnn^i Geogi-npluc.1 Imtituic THE VICTORIA HISTORY 01
The text on this page is estimated to be only 15.14%
accurate

UAL MAP. • EXPLANATION OF COLOURING RECENT 1


.IHnnnin IMI, Mf«4MM«k. II ..J«M* «"rf /(-.I /...; ,.,..! M.llwl /«•'.
County Boundary shown that HE COUNTIES OF ENGLAND
The text on this page is estimated to be only 28.75%
accurate

GEOLOGY ESSEX occupies a large part of the irregular tract


which is known to geologists as the London Basin, and which has for
its framework the great Chalk formation. The southern rim of this
Basin rises in the North Downs of Kent, whence the Chalk slopes
gradually to the borders of the Thames at Erith and Gravesend,
comes to the surface in south Essex at Purfleet and Grays, and then
sinks below ground over the greater part of the county. The northern
rim of the Basin appears in the downs of Dunstable, Luton and
Royston, and in the uplands of Heydon and Saffron Walden in Essex.
The contour of the Chalk Basin is to some extent modified by slight
undulations and fractures along the Kentish side of the Thames
between Greenwich and Erith, so that while the curvature is for the
most part gentle, the inclination becomes somewhat steeper on the
southern side of Essex. Hence at Dagenham, Rettenden and
Southend the Chalk is about 400 feet below ground, at Chelmsford it
is about 360 feet, and thence northward it more gradually
approaches the surface. Near Heydon however there are some
striking evidences of local disturbance, to which further reference
will be made. Resting in the hollow of the Basin, and conforming
generally with its curvature, is a series of Eocene strata, the most
important of which is the London Clay. The succeeding deposits
include small outlying tracts of Crag, but they consist chiefly of the
irregular and variable accumulations grouped as ' drift.' These lie
scattered over the uplands in the form of gravel and Boulder Clay,
and are spread along the river valleys in the form of gravel,
brickearth and alluvium. The structure of the ground is thus
comparatively simple, but there are difficulties in the determination
of the relative ages of some of the scattered superficial deposits.
There are grave difficulties also when it is sought to decipher the
underground rocky structure beneath the Chalk and other
Cretaceous strata. The problem is of the highest interest and
practical importance, but it raises questions which deep borings
alone can solve. Although the county is essentially a flat one, and
especially along the river and sea coasts which are bordered by
marshes, yet inland there is an abundant variety of soil, and these
regions are very pleasantly diversified with arable land and pasture,
with woodlands, commons and welltimbered hedgerows. Indeed to
quote an old agricultural work, ' Every species of soil, from the most
stubborn to the mildest loam, is to be found.'1 1 General firm of A
'grit. ofEtiex, by Messrs. Griggs, 410 (Lond. 1794), p. 7. I I '
The text on this page is estimated to be only 27.18%
accurate

A HISTORY OF ESSEX To the geologist the richly


fossiliferous strata of the Red Crag at Walton-on-the-Naze, and the
Pleistocene valley -deposits with their many notable remains of
mammalia and mollusca, have attracted a large share of attention.
Our knowledge of Essex geology, due chiefly to the labours of
Prestwich, Searles V. Wood, jun., Prof. W. Boyd Dawkins, and Mr. W.
Whitaker, has been augmented by the workers of the Essex Field
Club and of the Geologists' Association, and notably by Mr. T. V.
Holmes.1 The following is a Table of the Formations met with in
Essex, the names in italics referring to those not exposed at the
surface : — Period Formation Character of the strata Approximate
thickness in feet Alluvium Silt, peat, clay 2O to 50 Recent to Blown
Sand Fine sand about 1 5 Neolithic Marine Sand and Shingle . Sand
with shells and pebbles of flint, quartz, etc about 10 Brickearth Loam
i o to 30 Valley Gravel Sub-angular flint gravel . . 10 to 50
Pleistocene Boulder Clay Chalky clay, with flints and Palaeolithic
erratics 2O to 70 and Glacial Loam Loam 10 to 15 Glacial Glacial
Gravel and Sand Sub-angular gravel with flints, quart/.itc, etc 20 to
75 Older Plateau Gravel . . . Pebbles of flint and quartz . 5 to 12 Red
Crag . Red shelly sand and gravel, Pliocene laminated clay,
phosphatic nodules and ironstone . 5 to 21 Bagshot Beds Sand and
pebble beds . 20 to 40 London Clay Brown and blue clay with 400
Eocene Blackheath or Oldhaven Beds . Sand with shells and flint i o
to 50 Woolwich and Reading Beds . Mottled clay, sand, and flint 25
to 80 Thanet Beds Grey sand and sandy clay . • 10 to 85 Upper
Chalk Chalk with flints .... 400 to 450 Middle Chalk Bedded chalk
with few flints . 200 Upper Blocky chalk with curved Cretaceous
Upper Greenland jointing, and marl Green sand and brown loam .
120 7O Gault 5O to I7O S'tlurion ^ (or older) unknown 1 See
Bibliography in Whitaker's 'Geology of the London Basin,' Mem. Geol.
Survey, vol. i. (1872) p. 393 ; and Geology of London, vol. i. (i 889)
p. 87 ; also ' List of Works on the Geology, etc., of Essex,' by W.
Whitaker and W. H. Dalton, Essex Nat., vol. iii. (1889) pp. 61-84. 2
The text on this page is estimated to be only 28.24%
accurate

GEOLOGY PALAEOZOIC ROCKS The question whether


productive Coal Measures are likely to occur at a workable depth
beneath Essex is one which has aroused keen interest of late years.
So long ago as 1858 a boring at Harwich proved the occurrence of a
dark slaty rock beneath the Gault, at a depth of 1,029 ^eet from the
surface.1 It was then thought that this rock, which was penetrated
to a depth of 69 feet, was of Lower Carboniferous age owing to the
supposed occurrence in it of the fossil mollusc Posidonomya. The
specimen was however re-examined in 1896 by Prof. W. W. Watts,
and he came to the conclusion that, while the rock itself was not at
all like that of any known British Carboniferous rock, the supposed
fossil was an inorganic structure.1 A somewhat similar dark slaty
rock was touched at a depth of 994 feet in a trial boring in Suffolk,
at Stutton on the northern side of the Stour estuary ; and again in a
further trial in Essex, at Weeley between Colchester and Walton-on-
the-Naze, where the old rock was reached at a depth of 1,094 feet.8
These two trials in search of Coal Measures were made after due
deliberation with the highest geological authorities. That they were
unsuccessful is an indication, not that the chances of obtaining coal
beneath Essex are hopeless, but that scientific knowledge is
insufficient to tell precisely where concealed coal-basins occur.
Nevertheless enterprise need not be damped. There is always a
possibility of finding coal where the strata at the surface are newer
than the Coal Measures ; but as the older rocks were bent and
fractured and largely eroded before the Secondary and Tertiary
strata were spread over them, it is evident how speculative must be
the search for Coal Measures under these circumstances. Were the
exposed coalfields to be covered up with a mantle of Chalk, we
should have no certain guide from one successful boring as to the
nature of the deep-seated rocks at a distance of a few miles,
because there is no regularity in the preservation of coal-basins.
Again if rocks much older are proved in a boring, it is quite possible
that Coal Measures may exist near by, because in south
Staffordshire, Leicestershire and Warwickshire the older Palaeozoic
rocks occur in juxtaposition with productive Coal Measures. It has
lately been suggested by Prof. W. J. Sollas that Enfield Lock, just
across the Lea on the Hertfordshire side, is a likely place for a
successful trial. It may be so, but there is no information that would
prove that it is a more promising site than any other unproved
locality in Essex or Hertfordshire.4 In Essex several deep borings
have been made in search of water. Thus at Wickham Bishop a
boring was carried to a depth of 1,180 feet, 1 Prestwich, Quart.
Journ. Geol. Sot., vol. xiv. p. 252. * Ann. Report of Geol. Survey for
1896, p. 5. » Whitaker, Ref. Brit. Ante, for 1895. 4 For further
information on the underground rocks see Whitaker, Geology of
LenJen, vol. i. p. 10. (In this work full references are made to the
suggestions of Godwin-Austen, Prestwich and others on the older
deep-seated rocks.) 3
The text on this page is estimated to be only 28.02%
accurate

A HISTORY OF ESSEX including 703 feet of Chalk (base not


reached). It is probable that the thickness of the Eocene strata was
here to a certain extent duplicated by a reversed fault or fold.1 At
Loughton a boring was made to a depth of 1,100 feet into Gault ;
and at South Shoebury another was carried 1,048 feet, probably into
Lower Chalk. An old boring at Saffron Walden was carried to a depth
of a little over 1,000 feet, but the details of the strata cannot now be
interpreted with certainty. In all of these borings, if we except the
Palaeozoic rock, the oldest formation whose age has been proved is
the Gault. GAULT AND UPPER GREENSAND The Gault consists of stiff
blue and grey clay and marl, which was proved to have a thickness
of 172 feet in the deep boring at Loughton. It was found below
Harwich and Weeley, and is probably everywhere present beneath
the Chalk under Essex ; but it evidently becomes thinner towards
the north-east, as it was only 50 or 60 feet thick at Harwich. There is
evidence of the presence of Upper Greensand beneath a portion of
Essex along the Lea valley. Mr. Whitaker has remarked that this
formation was found beneath the Chalk at Cheshunt, and was met
with in the deep well at Loughton, the thickness being about 30 feet.
Below the Gault at Loughton there was sand, which may possibly
represent Lower Greensand.2 CHALK The Chalk appears at the
surface over a comparatively small portion of Essex, but where it
does occur its presence is usually indicated by pits and lime-kilns.
The Lower Chalk in Cambridgeshire includes at its base the
wellknown bed of phosphatic nodules and phosphatized fossils
termed the ' Cambridge Greensand,' but whether or not this bed
occurs underground in the northern part of Essex is unknown. Above
is the Chalk Marl, a mass of grey marl 50 or 60 feet thick, which
yields Ammonites variant, Inoceramus latus and other fossils. Still
higher we come to the Totternhoe Stone, a hard band of somewhat
sandy rock, which north of Heydon is a noted water-bearing stratum,
strong springs being thrown out at its junction with the Chalk Marl.
The Totternhoe Stone is characterized by Rbynchonella mantelliana,
Kingena lima, Pecten orbicularis and P. Jissicostata. The uppermost
portion of the Lower Chalk comprises a mass of grey chalk or clunch
which yields Belemnitella (Actinocamax) plena and Ho/aster
subglobosus? These portions of the Chalk do not appear at the
surface in Essex, but they no doubt occur everywhere below ground.
The Middle Chalk, which is exposed north of Heydon, at Great 1 See
Whitaker, Trans. Essex Field Club, vol. iv. pp. 149, 1 68. 2 Ibid. vol.
iv. pp. 158, 159 ; and Quart. Journ. Geol. Soc., vol. Ivi. p. Ixxv. ; and
Jukes-Browne, Cretaceous Rocks of Britain, vol. i. p. 370. 3 See W.
Hill and A. J. Jukes-Browne, Quart. Journ. Geol. Sue., vol. xlii. p.
216. 4
The text on this page is estimated to be only 28.28%
accurate

GEOLOGY Chesterford, Hadstock, and Sturmer near


Haverhill, includes at its base the Melbourn Rock, named from the
Cambridgeshire village of Melbourn. This is a hard rocky chalk with
marly and nodular layers, about ten feet in thickness. The mass of
the Middle Chalk above is well bedded in layers that appear to be
lenticular or wedge-shaped, and it has but few flints. Among the
fossils are Rhynchonella cuvieri, Terebratulina, and Ho/aster
subglobosus. The last-named fossil is found also in a band of hard
cream-coloured limestone with green coated nodules and grains of
glauconite, known as the Chalk Rock, which separates the Middle
from the Upper Chalk. The Chalk Rock has been observed in several
places in the northern portions of the county. Between Heydon and
Chishall the Chalk is locally disturbed, and instead of the normal
southerly or south-easterly dip at a gentle angle, the strata are
inclined at an angle of 25° N.N.W., and the flints are fractured. This
high dip increases to the south-west in Hertfordshire. Whether the
disturbance is due to faulting or to the surface derangements
produced by glacial agents has not been satisfactorily determined.
That glacial action has been potent is manifest from the deeply
excavated trough near Newport, to which reference will be made.
The Upper Chalk, which lies about 43 feet below the surface near
the Thames at Beckton, appears above ground at Grays and Purfleet
in south Essex ; and in the north it may be seen at Farnham and
Clavering in the Stort valley, at Quendon, Newport, Audley End and
Saffron Walden in the Cam valley, and eastwards at Great Yeldham
and Middleton, near Sudbury. It consists of soft chalk with layers of
flints, and yields remains of the saurian Leiodon (allied to
Mosasaurus), of fishes such as Ptycbodus polygyrus, molluscs
including Inoceramus and Lima, brachiopods such as Terebratula
carnea, the echinoderms Cu/aris and Goniaster, as well as crinoids
and corals. At Purfleet, Grays and West Thurrock the Chalk has been
largely used in the manufacture of whiting, lime and cement. At
Hangman's Wood a remarkable series of excavations known as
Deneholes occur. These are shafts carried through about 50 or 60
feet of gravel and Thanet Sand, and 20 feet or more into the Chalk,
but as their interest is mainly archaeological they will be described
elsewhere. There is no doubt that the Chalk has been used 'from
time immemorial ' for chalking the land, and more extensively in old
days. Arthur Young in 1768, after remarking on the badness of the
road between Billericay and Tilbury, observed that ' to add to all the
infamous circumstances, which concur to plague a traveller, I must
not forget the eternally meeting with chalk-waggons.' He mentioned
also that Chalk was brought from Kent by sea to Maldon.1 At Stifford
the Chalk has not only been worked in open pits, but also by means
of shafts or ' chalk-wells,' evidence of which was brought 1 A Six
Wteki Tour through the Southern Counties, p. 72 ; see also hi«
General P'ten eftbe Agritulture of Essex, vol. ii. (1807) p. 206. 5
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like