0% found this document useful (0 votes)
11 views84 pages

Data Structures and Algorithms With C Pal Debdutta Halder Suman Instant Download

The document is a comprehensive overview of the book 'Data Structures and Algorithms with C' by Debdutta Pal and Suman Halder, aimed at students in computer science and engineering. It covers fundamental concepts of data structures, algorithms, and their applications, structured into chapters that include arrays, linked lists, stacks, queues, trees, graphs, and sorting techniques. Additionally, it provides insights into memory management and file handling, making it a valuable resource for learners in the field.

Uploaded by

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

Data Structures and Algorithms With C Pal Debdutta Halder Suman Instant Download

The document is a comprehensive overview of the book 'Data Structures and Algorithms with C' by Debdutta Pal and Suman Halder, aimed at students in computer science and engineering. It covers fundamental concepts of data structures, algorithms, and their applications, structured into chapters that include arrays, linked lists, stacks, queues, trees, graphs, and sorting techniques. Additionally, it provides insights into memory management and file handling, making it a valuable resource for learners in the field.

Uploaded by

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

Data Structures And Algorithms With C Pal

Debdutta Halder Suman download

https://ebookbell.com/product/data-structures-and-algorithms-
with-c-pal-debdutta-halder-suman-10525336

Explore and download more ebooks at ebookbell.com


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

Data Structures And Algorithms With The C Stl A Guide For Modern C
Practitioners 1 Converted John Farrier

https://ebookbell.com/product/data-structures-and-algorithms-with-the-
c-stl-a-guide-for-modern-c-practitioners-1-converted-john-
farrier-55889290

Data Structures And Algorithms With Go Create Efficient Solutions And


Optimize Your Go Coding Skills Duan Stojanovi

https://ebookbell.com/product/data-structures-and-algorithms-with-go-
create-efficient-solutions-and-optimize-your-go-coding-skills-duan-
stojanovi-56153732

Handson Data Structures And Algorithms With Kotlin Chandra Sekhar


Nayak

https://ebookbell.com/product/handson-data-structures-and-algorithms-
with-kotlin-chandra-sekhar-nayak-11063708

Handson Data Structures And Algorithms With Rust Claus Matzinger

https://ebookbell.com/product/handson-data-structures-and-algorithms-
with-rust-claus-matzinger-57017412
Handson Data Structures And Algorithms With Rust Claus Matzinger

https://ebookbell.com/product/handson-data-structures-and-algorithms-
with-rust-claus-matzinger-170505490

Data Structures And Algorithms With Python 100 Coding Qa Code Of Code
Converted Yasin Cakal

https://ebookbell.com/product/data-structures-and-algorithms-with-
python-100-coding-qa-code-of-code-converted-yasin-cakal-54845986

Handson Data Structures And Algorithms With Python Write Complex And
Powerful Code Using The Latest Features Of Python 37 2nd Edition 2nd
Edition Dr Basant Agarwal

https://ebookbell.com/product/handson-data-structures-and-algorithms-
with-python-write-complex-and-powerful-code-using-the-latest-features-
of-python-37-2nd-edition-2nd-edition-dr-basant-agarwal-10684212

Data Structures And Algorithms With Python With An Introduction To


Multiprocessing Undergraduate Topics In Computer Science 2nd Ed 2023
Lee

https://ebookbell.com/product/data-structures-and-algorithms-with-
python-with-an-introduction-to-multiprocessing-undergraduate-topics-
in-computer-science-2nd-ed-2023-lee-55038848

Learn Data Structures And Algorithms With Golang Level Up Your Go


Programming Skills To Develop Faster And More Efficient Code Bhagvan
Kommadi

https://ebookbell.com/product/learn-data-structures-and-algorithms-
with-golang-level-up-your-go-programming-skills-to-develop-faster-and-
more-efficient-code-bhagvan-kommadi-10903012
Data Structures and
Algorithms with C
Data Structures and
Algorithms with C

Debdutta Pal
Suman Halder

α
Alpha Science International Ltd.
Oxford, U.K.
Data Structures and Algorithms with C
352 pages

Debdutta Pal
Suman Halder
Department of Computer Science and Engineering
Calcutta Institute of Engineering and Management
Kolkata

Copyright © 2018
A L P H A S C I E N C E I N T E R N AT I O N A L LT D .
7200 The Quorum, Oxford Business Park North
Garsington Road, Oxford OX4 2JZ, U.K.

www.alphasci.com

ISBN 978-1-78332-368-5

E-ISBN 978-1-78332-427-9

Printed from the camera-ready copy provided by the Authors.

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system,
or transmitted in any form or by any means, electronic, mechanical, photocopying, recording
or otherwise, without prior written permission of the publisher.
Dedicated
to
Our Parents
Preface

This book is designed as a stepping stone for the students to enter into the world of computer science
and engineering. All the students irrespective of different domain of technology if want to build carrier
in the Computer Science and Engineering domain have to have enough knowledge in data structures.
The Data structure is a course that helps students to accumulate knowledge about how data are stored
and manipulated in the memory of any computing device. This book is written for the students who have
knowledge about C and now are going to open their eyes in the domain of data structure. Hence, the
prospective audience for this book consists primarily of sophomores and juniors majoring in computer
science or computer engineering.
Chapter 1, in this book is designed in such a way that the students having no knowledge in data
structure can boldly step forward into the zone of data structure. This chapter has a detail overview on a
data structure that includes definition of data structure, the categorisation of data structure. Operation on
different data structure is also included in this chapter. The chapter ends with application of data structure.
Chapter 2, can be defined as a soul of this book. This chapter includes details of the algorithm.
Definition of algorithm, life cycle of algorithm. Time complexity and space complexity measurement is
explained in this chapter. Students will come to know about asymptotic notation and the manipulation
of asymptotic notation in this chapter. Classification of the algorithm is also a major part of this chapter.
In the chapter 3, array is defined in broad way. The chapter includes details of one dimensional (1-D)
array. Multidimensional array is also explained here. Address calculations of one and two dimensional
array are shown in this chapter. Representation of a sparse matrix is given here. Manipulation of string
is a major part of this chapter.
Chapter 4 can be defined as a heart of this chapter. This includes classification of pointers and array
of pointers. Dynamic memory allocation (DMA) is one of the major contributions in this chapter. Stu-
dents will learn about different predefined functions that are used for DMA. They will also build their
knowledge about need of DMA and the shortcomings of DMA. Dynamically allocated spaces are how
to de-allocate that is also explained here. Creation of one dimensional and two dimensional arrays using
dynamic memory allocation is explained here.
In the chapter 5, detail of another a linear data structure is described. The name of this data structure
is “Link List”. This chapter initiates with linear link list and finally it concludes with a doubly link list.
Creation, traversal, insertion, deletion, reverse operations on the single link list, circular link list and the
doubly link list are explained in broad way. Both algorithms and programs are given for each operation
to make this chapter more student approachable. This chapter is application of DMA.
Chapter 6 deals with different aspects of Stack and Queue. The first part of this chapter explains
Stack definition and basic operations on Stack. It is followed by the application of Stack in POSTFIX,
PREFIX expression. Implementations of Stack using link list and array are also included in this chapter.
Second part of this chapter is all about Queue. Definition of the Queue and basic operations on queue are
specified here. Then categorisation of Queue is also given here. Different types of Queues like circular
queue, de-queue and priority queue are explained with example. Each operation on Stack and Queue is
accompanied with algorithm and programs.
viii Preface
In chapter 7, recursion is explained in a comprehensive way. When students reach at this chapter
they have acquired knowledge about non recursive functions. After completion of this chapter, students
will come to know about recursive function. This chapter deals with the need of recursion, depth of
recursion, type of recursion and the shortcomings of recursive functions. This chapter concludes with
bags of programs on recursion that make students more familiar with recursion.
Chapter 8 involves a non-linear data structure. Until now the students accumulate their knowledge
about the linear data structure. With this chapter they will reveal another look of data structure. This
chapter focuses on Tree structure. This chapter initiates with binary tree followed by a binary search tree
and end with multi way search tree. Each type of tree structure is explained with some basic operations
on tree like creation, insertion of node, traversal, and deletion of nodes. Height balance tree is one of the
major contributions of this chapter.
Chapter 10 focuses on another very important part of data structure that is Graph. Here, the graph is
explained in detail. The chapter introduces the different terminology of graph like nodes, link, adjacent
node, complete graph, path, circuit, walk, degree of vertex, etc.; it is followed by the memory repre-
sentation of the graph. Then memory representation of a graph is explained in terms of the adjacency
matrix, adjacency list, multi list, incident matrix. Then different graph traversal algorithm is explained.
Spanning tree formation is also shown here by the means of Prim’s algorithm and Kruskal algorithm.
The chapter also includes some algorithm to find shortest path using Bellman-Ford algorithm, Dijkstra’s
algorithm, and Floyed-Warshall algorithm. The chapter concludes with different application of graph in
different aspects of computer science and engineering fields. To make it easy -for student programs are
also written for all the algorithm explain in this chapter. Some lemmas are written for students who are
going to study design analysis and algorithm.
In chapter 10, different types of searching and sorting algorithms are explained. For each searching
and sorting algorithm recurrence relation is also derived using different approaches. The algorithms are
explained with the help of examples in each case. Each sorting and searching algorithm is accompanied
with programs so that the students can easily understand the algorithm and run the program without any
difficulties. This chapter includes some basic sorting algorithm like bubble sort, insertion sort, merge
sort, quick sort and also some advance sorting technique like radix sort, heap sort and shell sort.
Chapter 11 deals with hashing technique. It explains different terminology relates to hashing like
hash function, hash table. This chapter also describes different types of hashing procedure with examples.
Collision resolution techniques are also described in this chapter. Here, creation of hash table, insert in
a hash table and delete from a hash table is explained with algorithm and program.
Chapter 12, the concluding chapter of this book gives a glimpse on file handling. Here, different
ways of storing records in a file are explained. Indexing of records and searching of records from a file
are also described in this chapter.

Debdutta Pal
Suman Halder
Acknowledgement

I am grateful to the Almighty, whose grace and blessings empowered me at every juncture. This book
would not be completed without the contribution and support that I have acquired from many people. I
would like to take the opportunity to express my heartfelt thanks to these individuals.
I would like to thank my co-author Mr. Suman Halder, who encourage me to contribute in this book.
I am very grateful to my colleagues Mrs. Smita Basu, Mr. MD.Sahid Ahmed and Mr, Sudipta Basak for
their valuable suggestions. I wish to acknowledge my student whose feedback helps me to make this
book student centric.
Narosa Publishing House deserves my sincere thanks for providing me such a platform to share my
knowledge with the universe.
Last but not the least, a word of thanks goes to my parent’s in law, my beloved father Dipak Barman
Roy and mother Mala Barman Roy, my husband Supriyo Pal and my little daughter Ishaani . Without
their love, patience and continuous encouragements I would never be able to complete this book.

Debdutta Pal

The successful completion of any task would be incomplete without giving gratitude to the people who
made it possible and whose constant encouragement made these efforts with success. The acknowledge-
ment transcends with my deep gratitude to all the people, who inspired, supported and helped me in the
completion of this book.
I express my deep-felt thanks to the co-author Dr. Debdutta Pal, who continuously inspires me in
the completion of this book. I am very grateful to my colleagues at Calcutta Institute of Engineering and
Management, Mrs. Smita Basu, Mr. MD.Sahid Ahmed and Mr, Sudipta Basak for their valuable construc-
tive suggestions and genuine feedback. I extend my thanks to Mr. Surjakanta Sasmal who provided me
valuable materials.that helped me in writing this book.
I would like to thank the management, editorial and production unit of Narosa Publishing House,
for publishing this book in time. Suggestions and queries are most welcome through publishers.
Last but not the least, a word of thanks goes to my beloved parents, my elder sister, wife Rupa and
my little son Avinaba for their love, constant encouragement and blessings.

Suman Halder
Contents

Preface vii
Acknowledgments
ix

CHAPTER 1 INTRODUCTION 1.1


Data and Information 1.1
Representation of Data 1.2
Data Type 1.3
Data Structure 1.3
Classifications of Data Structures 1.4
Application of Data Structures 1.6
Abstract Data Type 1.6
Operations Perform on Data Structure 1.7
Overview of Different Data Structures 1.7
Summary 1.8
Exercises
1.8

CHAPTER 2 ANALYSIS OF ALGORITHM 2.1


Algorithm 2.1
Types of Algorithm 2.1
Algorithm Development Life Cycle 2.2
Analysis of Algorithm 2.3
Space Complexity 2.4
Time Complexity 2.5
Asymptotic Notations 2.7
Growth functions of Algorithm 2.10
Manipulation of Asymptotic Notations 2.13
Summary 2.15
Exercises 2.15
CHAPTER 3 ARRAY AND STRING 3.1
Array 3.1
One-dimensional array 3.1
xii Contents
Address calculation in One-dimensional array 3.5
Multi-dimensional array 3.5
Address calculation in two-dimensional array 3.6
Operations Perform on Array 3.9
Applications of Array 3.15
Representation of Polynomials 3.15
Sparse Matrix 3.16
Strings 3.21
Array of strings 3.23
Operations Perform on Strings 3.24
Summary 3.31
Exercises 3.31
CHAPTER 4 POINTER 4.1
Pointer Declaration 4.1
Address of Operator 4.1
Indirection Operator 4.3
Null Pointer 4.4
void Pointer 4.5
Generic Functions 4.6
Dangling Pointer 4.8
Arithmetic Operation with Pointer 4.8
Pointer to Pointer 4.8
Pointers and Arrays 4.13
Array of Pointers 4.15
Pointer to an Array 4.15
Pointer to Function 4.16
Passing addresses to Function 4.17
Function returning Pointer 4.18
Dynamic Memory Allocation 4.19
Creating one-dimensional array 4.22
Creating two-dimensional array 4.23
Pointers, Arrays and Strings 4.27
Summary 4.28
Exercises
4.28

CHAPTER 5 LINKED LIST 5.1


Limitations of Array 5.1
Linked List 5.2
Singly Linked list 5.3
Contents  xiii
Operations on Singly linked list 5.3
Representation of polynomials using linked list 5.17
Circular Linked list 5.19
Operation on Circular Link List 5.20
Josephus Problem 5.25
Doubly Linked list 5.26
Operation on Doubly Link List 5.26
Circular Doubly Linked List 5.36
Disadvantages of Linked List 5.37
Summary 5.37
Exercises
5.37
CHAPTER 6 STACK AND QUEUE 6.1
Stack 6.1
Operations on Stack 6.1
Stack Representation with Array 6.2
Stack Representation with Linked List 6.4
Processing of function calls 6.5
Evaluation of Arithmetic expressions 6.6
Queue 6.11
Operations on Queue 6.11
Queue Representation with Array 6.12
Queue Representation with Linked List 6.13
Application of Queue 6.14
Drawback of Linear Queue 6.14
Circular Queue 6.15
Circular Queue Representation with Array 6.15
Dequeue 6.16
Operation on DeQueue 6.17
Priority Queue 6.17
Representation of Priority Queue 6.18
Summary 6.19
Exercises 6.20
CHAPTER 7 RECURSION 7.1
Recursion Essentials 7.1
Infinite Regress 7.1
Depth of Recursion 7.2
Recursion Tree 7.2
Types of Recursion 7.2
xiv Contents
Factorial 7.6
Fibonacci Sequence 7.7
GCD 7.8
Integer Power 7.8
Tower of Hanoi 7.10
Non-attacking Eight Queens 7.12
Converting Recursive function to Iterative 7.16
Summary 7.17
Exercises 7.17
CHAPTER 8 TREE 8.1
Terminology of Tree 8.1
Binary Tree 8.2
Strictly Binary Tree 8.3
Extended Binary Tree 8.3
Complete Binary Tree 8.4
Full Binary Tree 8.4
Skewed Binary Tree 8.5
Binary Expression Tree 8.5
Balanced Binary Tree 8.7
Threaded Binary Tree 8.8
Properties of Binary Tree 8.9
Representation of Binary Tree 8.10
Binary Tree Traversal 8.13
Binary Search Tree 8.18
Operations on Binary Search Tree 8.18
Heap 8.26
Operations on Heap 8.27
AVL Tree 8.27
Operations on AVL Tree 8.27
Red-Black Tree 8.39
Multi-way Search Tree 8.40
B-Tree 8.41
Operations on B-Tree 8.42
2-3 Tree 8.50
2-3-4 Tree 8.50
Summary 8.51
Exercises 8.51
Contents  xv

CHAPTER 9 GRAPH 9.1


Terminology of Graph 9.1
Terminology of a Directed Graph 9.6
Operations on Graph 9.9
Representation of Graph 9.9
Graph Traversal 9.16
Spanning Trees and Minimum Spanning Trees 9.21
Kruskal’s Algorithm 9.23
Prim’s Algorithm 9.24
Shortest Paths 9.25
Dijkstra’s Algorithm 9.26
Bellman-Ford Algorithm 9.27
Floyd-Warshall Algorithm 9.28
Travelling Sales Man Problem 9.30
Summary 9.32
Exercises
9.32

CHAPTER 10 SEARCHING AND SORTING 10.1


Linear Search 10.1
Binary Search 10.3
Interpolation Search 10.6
Bubble Sort 10.8
Insertion Sort 10.12
Selection Sort 10.14
Quick Sort 10.15
Merge Sort 10.20
Heap Sort 10.24
Radix Sort 10.33
Shell Sort 10.35
Time complexity of Sorting Algorithms 10.37
Summary 10.38
Exercises 10.38
CHAPTER 11 HASHING 11.1
Hash Table 11.1
Hash Function 11.1
Division Method 11.2
Mid Square method 11.2
Folding method 11.3
xvi Contents
Collision Resolution 11.3
Linear Probing 11.4
Quadratic Probing 11.7
Double Hashing 11.9
Separate Chaining 11.10
Load Factor 11.12
Summary 11.12
Exercises
11.12

CHAPTER 12 FILE STRUCTURE 12.1


Elements of File System 12.1
Category of File Organisation 12.2
Sequential File Organisation 12.3
Heap File Organisation 12.3
Hash File Organisation 12.4
Index Sequential File Organisation 12.4
Primary Index 12.4
Secondary Index 12.6
Clustering 12.6
Multilevel Index 12.7
B tree 12.7
B+ tree 12.7
Summary 12.10
Exercises 12.10

Appendix A A.1
Solved GATE Question Papers SP.1
Glossary G.1
Bibliography B.1
Index I.1
CHAPTER 1

INTRODUCTION
“Those who wise succeed must ask the right preliminary questions”. – Aristotle

I
n Computer Science, one of the core fields that belongs to its
foundations, with the design, analysis, and implementation of K E Y F E A T U R E S
algorithms for the efficient solutions of the problem  Data and Information
concerned. The data structure is one of the subjects that
 Data Structure
intrinsically connected with the design and implementations of
efficient algorithms.  Data Type
The subject ‗Data Structure‘ deals with the study of methods,  Abstract Data Type
techniques, and tools to organize or structure data in computer
 Classification of Data Structure
memory.
Now before defining Data Structure, we should know ― what is data?‖ and ―
what is the difference
between data and information?‖
Data and Information
Data is a plural of datum, which is originally a Latin noun meaning ― something given.‖
The Oxford dictionary meaning of data is:
i) Facts or statistics used for reference or analysis.
ii) The quantities, characters or symbols operated by a computer.
For our purpose, the second meaning is more important. Therefore, we can say that:
The data represent quantities, characters, or symbols on which operations are performed by
a computer, stored and recorded on either magnetic, optical, or mechanical recording media, and
transmitted in the form of digital electrical signals.
Definition: Data is the basic entity or fact that is used in a calculation or manipulation process.
Data is commonly processed by some stages. Unprocessed data or raw data is a collection of
numbers, characters, that may be considered as an input of a stage and processed data is the output of
the stage.
There are two types of data, such as numerical and alphanumerical data. Data may be a single
value or a set of values and it is to be organized in a particular fashion. This organization or structuring
of data will have a profound impact on the efficiency of the program.
Most of the individuals consider that the terms "Data" and "Information" are interchangeable and
mean the same thing. However, there is a distinct difference between the two words. Data are raw
facts without context, whereas Information is data with context. Data are an abstraction of Information
in a problem-solving system. Data requires interpretation to become an Information.
Data can be any character, text, words, number, pictures, sound, or video and if not put into
context means nothing to a human or computer. For example, 10409 is a data, whereas information
1.2 | Data Structures and Algorithms with C
may be 1/04/09-the date of birth of Avinaba, 10409 a zip code of somewhere or Rs. 10409 is the salary
of someone.
Raw Data Information

Processing
Figure 1.1: Data and Information

Representation of Data
Almost all the high-level languages, e.g. FORTRAN, COBOL, C, Pascal, C++, Java, etc. allow data to
be represented in computer memory of mainly two types:
i) Numerical Data
ii) Alphanumerical Data
Most of the high-level languages classified numerical data into two types:
i) Integer
ii) Floating-point
In C language, the following Data types are used to represent numerical data.
Table 1.1: Ranges of numerical data types

Data types Memory requirement Ranges


char or signed char 1 byte -128 to +127
unsigned char 1 byte 0 to 255
short signed int or short int
2 bytes -32768 to +32767
or signed int or int
long signed int or long int 4 bytes -2147483648 to +2147483647
signed int or int ( for 32 bit compiler) 4 bytes -2147483648 to +2147483647
unsigned int 2 bytes 0 to 65,535
long unsigned int 4 bytes 0 to 4294967295
float 4 bytes -3.4e38 to +3.4e38
double 8 bytes -1.7e308 to +1.7e308
long double 10 bytes -1.7e4932 to +1.7e4932
Integer
For small integer data, most of the high-level languages generally use two bytes to represent both
positive and negative decimal integers. Negative integer numbers are represented by 2‘s complement
notation. For large integer data, generally, four bytes are used to represent both positive and negative
decimal integers.
Floating-Point
In the representation of small floating-point data, most of the high-level languages, e.g. C language,
use four bytes for fractional decimal numbers. For large numbers, double and long double are used to
accommodate in memory.
Alphanumerical data are classified into two types:
i) Character
ii) String
Introduction | 1.3

Character
The characters may be alphabets, digits, special characters and white spaces. In C language, characters
are represented by char data type and one-byte memory space is used for storing the same. The ASCII
format has been used in C language to represent the characters. While storing character ‗C‘ in the
computer, ASCII value 67 is stored in memory.
String
The string is a sequence of characters may consist of any number and any combination of characters.
The characters may be alphabets, digits, special characters and white spaces. In C language, the string
can be defined as an array of character terminated with a null character.
Data Type
Generally, computer programs do exist for a single purpose: how to process data. The type of data, the
format of data that is going to be returned and the correctness of the processing are the primary
concerns of a computer program. When a program is written, how the computer handles the data
internally is usually a secondary concern.
Definition: A data type refers to the type of data that variables hold.
Now, depending on the representation of different forms of data, different data types are used. The
data types are names given to a set of variables, which have common properties. A data type refers to
the type of data that variables hold.
Data types

Primary Data types Derived Data types User-defined Data types

char int float double void

Figure 1.2: Data Types

The C language supports three classes of data types:


i) Primary or Basic data types
ii) Derived data types
iii) User-defined data types
Basic or primary data types are language built-in. The C language supports five primary or basic
data types. They are
i) char ii) int iii) float iv) double v) void
Data Structure
Data Structure is the representation of the logical relationship between individual elements of data. In
Computer Science, Data Structure is defined as a mathematical or logical model of organizing the data
items into computer memory in such a way that they can be used efficiently. The purpose of studying
1.4 | Data Structures and Algorithms with C
data structure is to learn how to organize data into memory so that it can be accessed quickly and
conveniently.
Data Structure refers to the study of data and representation of data objects within the program;
i.e., the implementation of structured relationships among different data objects.
Example: lists, stacks, queues, heaps, search trees, hash tables, etc.
Different sets of operations can be performed on different data structures. The operations that can
be performed on different data elements within a data structure are accessing, traversing, inserting,
deleting, modifying etc. While writing a program, a minimal data structure must be chosen that
supports all the operations as per need.
Data Structure can be used for the following purpose:
i) Organizing the data – How data items are organized in the main memory?
ii) Accessing methods – How data items can be accessed?
iii) Specifying the degree of associativity – How data items are interrelated?
iv) Processing alternatives for data – How many different ways are there in which these data
items can be processed?
A program is a set of instructions, which involve a computer performing some kind of
computation or algorithm. Data Structure affects the design of both structural and functional aspects of
a program. To implement a program of an algorithm, we should select an appropriate data structure for
that algorithm. Therefore, the programs are inherited by an algorithm and its associated data structure.
Algorithm + Data Structure = Program
Programming languages provide facilities for representatives of algorithm and data. High-level
Programming Language, like C, facilitates structured and modular programming by providing
algorithm structures.
Classifications of Data Structure
Data Structure can be classified into two categories:
i) Primitive data structure
ii) Non-Primitive data structure
Primitive Data Structure
The primitive data structures are defined that can be manipulated or operated by the machine
instruction. There are numerous types of data structures, generally built upon simpler primitive data
types, called Primitive data structures, which are represented in computer memory.
Example: Integer, floating point, characters, pointer, boolean, etc. are some of the different
primitive data structure.
In C language, the different primitive data structures are defined using the data type such as int,
char, float, double etc.
Non-primitive Data Structure
The non-primitive data structures are a data structure that cannot be manipulated or operated directly
by the machine instructions. These are more sophisticated data structures. Non-primitive data
structures are derived from the primitive data structure. These are a group of homogeneous or
heterogeneous data items.
Example: Arrays, structure, stack, queues, linked lists etc.
Introduction | 1.5
The Non-primitive data structures are classified into two categories:
i) Linear data structure
ii) Non-linear data structure

Data
Structure

Non -
Primitive
primitive

Non -
int float char pointer Linear
Linear

Sequential Linked Graph Tree

Linked Linked Linked


Array Stack Queue
List Stack Queue

Figure 1.3: Classification of Data Structure

Linear Data Structures


The data structure is linear if every data item is related to its previous and next data items (e.g., array,
linked list). In the linear data structure, data items are arranged in memory in a linear sequence and
data items are accessed linearly. The traversing of the linear data structure is exactly once.
Linear data structures are two types:
i) Sequential
ii) Linked
Sequential Data Structures are based on arrays where objects are stored in a sequence of
consecutive memory locations.
Example: Arrays, Stacks, Queues
Linked Data Structure is a data structure, which consists of a set of nodes linked together and
organized with links.
Example: Linked Lists, Linked Stacks, Linked Queues
Non-linear Data Structures
A data structure is non-linear if every data item attaches to many other data items in specific ways to
reflect relationships (e.g., tree). In non-linear data structures, the data elements are not in sequence, i.e.,
insertion and deletion are not possible in a linear manner. The traversing of the non-linear data
1.6 | Data Structures and Algorithms with C

structure is always more than one.


Example: Graphs, Trees
Static Data Structure
The static data structure is a kind of data structure, in which once memory space is allocated it cannot
extend, i.e. the memory allocation for the data structure takes place at compile-time that cannot be
changed afterwards.
Example: Array
Dynamic Data Structure
Dynamic Data Structure is another kind of data structure, which can be extended or shrink during the
execution, i.e., the memory allocation as well as memory de-allocation for the data structure takes
place at run-time and allocates memory as required amount at any time.
Example: linked list, stack, queue, tree
Applications of Data Structure
Different Data Structure is used in real life, such as the representation of an image in the form of a bit-
map, implement printer spooler so that jobs can be printed in the order of their arrival, store
information about the directories and files in a system, etc. Data Structure is used in various fields of
Computer Science, such as:
 Compiler Design
 Operating System
 Database Management System
 Statistical Analysis Package
 Numerical Analysis
 Graphics
 Artificial Intelligence
 Simulation
Different kinds of data structures are suitable for different kinds of applications. Some data
structures are highly specialized for specific tasks. For example, databases use B-tree indexes for small
percentages of data retrieval, and compilers and databases use dynamic hash tables as lookup tables,
operating systems use queues for process management, I/O request handling.
Abstract Data Type
A data type refers to the type of data that variables hold. Thus, integer, real, characters are referred to
as primitive data types.
Data Object represents an object having a data. The study of classes of objects whose logical
behavior is defined by a set of values and a set of operations.
Definition: An Abstract Data Type (ADT) describes the data objects, which constitute the data
structure and the fundamental operations supported on them.
An ADT promotes data abstraction and focuses on what a data structure does, rather than how it
implements (does).
 An ADT is a conceptual model of information structure.
 An ADT specifies the components, their structuring relationships and a list of operations that
Introduction | 1.7
are allowed to perform.
 It is just a specification, no design or implementation information is included.
 Specification involves the ― what‖ the operations, not the ―
how‖.
 ADT‘s are generalizations of primitive data types.
A data structure is the design representation of an ADT.
 The same ADT may be represented by several data structures.
 There are many data structures corresponding to the ADT ― set‖.
Operations Perform on Data Structure
Data are processed by means of certain operations, which appear in the data structure. The particular
data structure is chosen largely depends on the frequency of the operation that needs to be performed
on the data structure. Different kinds of operations are to be performed on data structures.
Table 1.2: Operations on Data Structures

Operation Description
Allocation of memory for the data structure, the creation of data structure
Creation
may take place either during compile-time or during run-time.
Insertion Insert a data item in the data structure.
Deletion Delete a data item from the data structure.
Traversing Accessing and processing each data item of the data structure exactly once.
Searching Find the location of the key value within the data structure.
Arranging all the data items in a data structure either in ascending or in
Sorting
descending order or in lexicographical order (for Strings).
Merging Combining the data items of two different sorted lists into a single sorted list.

Overview of Different Data Structures


Different data structures can be defined as follows:
Array
An array is a collection of the same type of data items, which are stored in consecutive memory
locations under a common name. In arrays, there is always a fixed relationship between the addresses
of two consecutive elements as all the items of an array must be stored contiguously.
Stack
A stack is a collection of elements into which new elements may be inserted and from which elements
may be deleted only at one end called the top of the stack. Since all the insertion and deletion in a stack
is done from the top of the stack, the last added element will be first to be removed from the stack.
That is the reason why stack is also called Last-In-First-Out (LIFO) data structure.
Queue
A queue is a homogeneous collection of elements in which deletions can take place only at the front
end, known as dequeue and insertions can take place only at the rear end, known as enqueue. The
element, which inserts in the queue first, will delete the queue first. In this order, a queue is called
First-In-First-Out (FIFO) system.
1.8 | Data Structures and Algorithms with C

Linked List
A linked list is an ordered collection of finite homogeneous data elements called node where the linear
order is maintained by means of links or pointers. In linked list, data items may be scattered arbitrarily
all over the memory. In a linked list, there is no relationship between the addresses of elements; each
element of a linked list must store explicitly the address of the element, next to it.
Tree
The tree is a non-linear data structure. A Tree may be defined as a non-empty finite set of nodes, such
that
i) There is a specially designated node called the root,
ii) The remaining nodes are partitioned into zero or more disjoint trees T 1, T2, … Tn are called the
subtrees of the root R.
Graph
The graph is another non-linear data structure. A Graph G is defined as an ordered set G = (V, E),
consists of finite non-empty set of objects V, where V (G) = {v1, v2, v3, … vn} called vertices (or nodes
or points) and another set E where E (G) = {e1, e2, e3, …em} whose elements are called edges, that
connects these vertices.
Summary
 Data is the basic entity or fact that is used in the calculation or manipulation process.
 Data are raw facts without context, whereas information is data with context.
 Data Structure is defined as a mathematical or logical model of the particular organization of data
items in computer memory so that it can be used efficiently.
 An Abstract Data Type (ADT) describes the data objects, which constitute the data structure, and
the fundamental operations supported on them.
Exercises
1. What are the differences between linear and non-linear data structures?
2. What are the operations can be performed on data structures?
3. What is an Abstract Data Type? What do you mean by a Dynamic Data Structure?
4. Choose the correct alternatives for the following:
i) Which of the following data structure is a linear data structure?
a) Trees b) Graphs c) Arrays d) None of these
ii) The operation of processing each element in the list is known as
a) Sorting b) Merging c) Inserting d) Traversal
iii) Finding the location of the element with a given key in the list is known as
a) Traversal b) Searching c) Sorting d) None of these
iv) Representation of data structure in memory is known as
a) Recursion b) Abstract data type c) Storage structure d) File structure
v) An ADT is defined to be a mathematical model of a user-defined type along with the collection
of all__________operations on that model
a) Cardinality b) Assignment c) Primitive d) Structured

*****
CHAPTER 2

ANALYSIS OF ALGORITHM
“Programming is the art of telling another human being what one wants the computer to do”. –
Donald Knuth

A n algorithm is a well-defined computational procedure that


transforms inputs into outputs achieving the desired input-
KEY FEATURES
output relationship. We must design a process to solve a  Algorithm
specific problem before programming. This process must be  Types of Algorithm
formulated as a detailed sequence of basic steps, which is called an
algorithm. An algorithm can perform the calculation, data processing  Time Complexity
and automated reasoning task in a finite time.  Space Complexity
The word ― algorithm‖ is a Persian word algorism derived from  Asymptotic Notations
the name of the Persian author and great mathematician ― Abu Abd
Allh Jafar Mohammad bin Musba al Khowarzimi‖ (Born in 780 A.D. in Baghdad). He worked on
algebra, geometry, and astronomy. He designs the first algorithm for adding numbers represented in
the numerical system.
ALGORITHM
Definition: Algorithm is a finite sequence of instructions/steps, each of which is very elementary that
must be followed to solve a problem.
All algorithms must satisfy the following criteria:
 Input: There are some inputs (zero or more quantities), which are externally supplied.
 Output: The result (at least one quantity) should be produced after completion of the job to
the user.
 Definiteness: The instructions should be unique, concise, clear and unambiguous.
 Finiteness: The instructions should be relative in nature and should not be of an infinite type.
Should be terminated after a finite number of steps.
 Effectiveness: Every instruction must be elementary, so that it can be carried out, in principle,
by a person using only pencil and paper. Repetition of same steps should be avoided. It must
be feasible.
Types of Algorithms
Algorithms that use a similar problem-solving approach can be grouped together. This classification
scheme is neither exhaustive nor disjoint. The purpose of this classification is to highlight the various
ways in which a problem can be solved. Using different techniques, one can develop many algorithms
for the same problem. These techniques are not only applicable in Computer Science but also to other
fields such as Operation Research, Electrical Engineering etc. We can formulate/develop a good
algorithm by studying all the techniques.
2.2 | Data Structures and Algorithms with C
Algorithm types we will consider
 Divide and conquer
 Dynamic programming
 Greedy Method
 Backtracking
 Branch and Bound
 Serial or parallel or distributed algorithm
 Deterministic or non-deterministic algorithm
Algorithm Development Life Cycle
In the life cycle of an algorithm for the development of an algorithm, the following phases are
involved:
i) Algorithm design / Design Phase
ii) Writing Phase
iii) Testing / Experiment Phase
iv) Analysis of Algorithm / Analysing Phase
Algorithm Design
Algorithmic design patterns, which provide general techniques for designing algorithms, including
divide-and-conquer, dynamic programming, greedy method, backtracking, and branch-and-bound. In
the design phase of an algorithm, one of the algorithmic design techniques and the data structure is
used.
Writing Phase
An algorithm generally is written in a modular approach. An algorithm may have the following
structures or steps:
Input Step, Initialization Step, Assignment Step, Decision Step, Repetition Step and Output Step.
To make each and every step clear in the algorithm, comments are written whenever necessary.
An algorithm is written using the following basic methods:
 Sequential: Steps are performed sequentially.
 Selection/Decision: One of the several alternative actions is selected.
 Repetition: One or more than one step(s) are performed repeatedly.
The following example describes a formal representation of an algorithm that converts
temperature from Celsius to Fahrenheit.
Algorithm to convert temperature from Celsius to Fahrenheit.
Algorithm: Convert(C, F)
[The variable C is used as Celsius value and F is used as Fahrenheit
value]
1. Read C
2. Set F = 1.8 * C + 32
3. Print F
4. Return
Analysis of Algorithm | 2.3
The following algorithm calculates the summation of N natural numbers. First, we have to read the
value of N.
Algorithm to calculate the sum of N natural numbers.
Algorithm: Sum (N)
[The variable N is represented the number of natural numbers.]
1. Set S = 0 and I = 1
2. Read N
3. S = S + I
4. I = I + 1
5. If I<=N Goto Step 3
6. Print S
7. Return
Searching refers to the operation of finding the location of any element in the array. The search is
successful if the item is found; otherwise, it is unsuccessful. Linear search is a method where the
search starts from the beginning of the array until the desired key is found or the end of the array is
reached.
Algorithm of Linear search.
Algorithm: Linear_Search (A, N, Key)
[An array A with N elements and an item Key are given. This
algorithm searches the location of the Key in the array A]
1. Set I = 1
2. Repeat Steps 3 while I <= N and A[I]≠ Key
3. I = I + 1
[End of while]
4. IF I <= N then
Print: Item found at location I
Else
Print: Item not found
[End of IF]
5. Return
Testing Phase
After writing an algorithm, it is necessary to check whether the algorithm is correct or not. One must
perform each step using paper and pencil by some required valid input, use the algorithm and get the
required output in a finite time. Testing or Experiment is another step in the development of the
algorithm. When any error is found, then go back to the algorithm design phase and redesign the
algorithm.
Analysis of Algorithms
Algorithms are to be analysed to compute the objective criteria for different input size before actual
implementation. Suppose P is a problem and A & B are two different algorithms to solve the problem
P. There must have some performance measurement system to decide that which algorithm is better
than the other.
Suppose M is an algorithm and n is the size of the input data. The time and space used by the
2.4 | Data Structures and Algorithms with C
algorithm M are two main measures for the efficiency of M.
The complexity of an algorithm M is the function f (n) which gives the running time and/or
storage space requirement of the algorithm in terms of the size n of the input data.
There are some qualitative aspects of algorithms, e.g., simplicity, readability, modularity,
modifiability, well documented, etc. However, based on these, there can only be some subjective
judgment about algorithms. Moreover, the objective criteria for the qualities of an algorithm are the
amount of memory used and execution time.
Therefore, the performance of the algorithm can be measured on the scales of time and space.
Time means, we are looking for the fastest algorithm for the problem. Space means we are looking for
an algorithm that consumes or needs minimum memory space for its execution.
When performance is measured in terms of space, it is known as space complexity and when
performance is measured in terms of time, it is termed as time complexity.
There are two kinds of analysis of algorithm may be possible:
i) Apriori Analysis
ii) Posteriori Analysis
Theoretical / Apriori Analysis
Apriori meaning "from the earlier". It is on a theoretical basis, independent of programming languages
and machine structures. Here, we do analysis (space and time) of an algorithm prior to running it on a
specific system. That means we can determine time and space complexity of an algorithm of getting
the algorithm rather than running it on a particular system (with different processor and compiler). The
stress is laid on the frequency of execution of statements in the algorithm.
Empirical / Posteriori Analysis
Posteriori means "from the latter". The actual amount of space and time taken by the algorithms are
recorded during execution. It is dependent on the programming language used and machine structure.
Here, we do an analysis of the algorithm only after running it on the system. It directly depends on the
system and changes from system to system.
In real-life, we cannot do posteriori analysis as software is generally made for an anonymous user,
which runs it on a system different from those present in the industry. Therefore, in Apriori analysis,
we use asymptotic notations to determine time and space complexity as they change from computer to
computer but asymptotically they are same
Space Complexity
The space complexity is the amount of space (memory) is needed for an algorithm to solve the
problem. An efficient algorithm takes space as small as possible.
Space needed by a program is the sum of the following components:
1. Instruction space: Space needed to store the executable version of the program and it is fixed.
2. Data Space: Space needed to store all constants, variable values and has further following
components:
a) Space needed by constants and simple variables. This space is fixed.
b) Space needed by fixed sized structured variables, such as arrays and structure.
c) Dynamically allocated space from memory pool called heap. This space usually varies.
3. In-build stack space: Space needed to store the information needed to resume the suspended
functions. Each time a function, the following data is saved on the In-build stack.
Analysis of Algorithm | 2.5
d) Return address i.e. from where it has to resume after completion of the called function.
e) Values of all local variables and the values of formal parameters in the function being
involved.
In general, the total space needed
1. Fixed Space Requirement: Includes space for code, space for simple variables, constants.
2. Variable Space Requirement: Includes space needed by component variables, structured
variable and dynamically allocated space and the recursive stack space.
Therefore, space complexity of a program P is
S (P) = C + Sp (I)
Where C is the fixed space requirement independent of a particular problem and Sp (I) is the
variable Space requirement depends on the instance characteristics I. Space complexity can express
that result in big O notation. Consider the following algorithm.
Algorithm: INT SUM (A, N)
1. IF N ≠ 0 then return SUM (A, N-1) + A [N-1]
2. Return 0
The above recursive function for summing a list of numbers, memory space is required for each
recursion call of the function, 2 bytes of the parameter A, 2 bytes for the parameter N and 2 bytes for
the return value. The total space required per recursive call 6 bytes and N number of recursive calls are
required to summing the list. Therefore, we get SSUM (I) = SSUM (n) = 6n.
Hence, we can write the space complexity of the above function in big-O notation is O (n).
Often, there is a time-space trade-off in a problem, where we compromise; that is, we cannot have
both low computing time and low memory consumption, so depending on the algorithm we choose
whether low computing time is essential or memory consumption.
Time complexity
The time complexity of an algorithm is a number of computer time needs in execution to complete. It
allows comparing the algorithms to check which one is efficient.
There are different factors affecting the execution time, e.g. programmer skills, compiler options,
hardware characteristics (instruction set, clock speed), the algorithm used, input size, etc. Generally, an
estimate of the growth rate of execution time with input size is sufficient for comparison.
The rules for computing running time
1. Sequence: Add the time of the individual statements. The maximum is the one that counts.
2. Alternative structures: Time for testing the condition plus the maximum time taken by any of
the alternative paths.
3. Loops: Execution time of a loop is at most the execution time of the statements of the body
(including the condition tests) multiplied by the number of iterations.
4. Nested loops: Analyze them inside out.
5. Subprograms: Analyze them as separate algorithms and substitute the time wherever
necessary.
6. Recursive Subprograms: Generally, the running time can be expressed as a recurrence
relation. The solution of the recurrence relation yields the expression for the growth rate of
execution time.
Now, Time taken by a program P means,
2.6 | Data Structures and Algorithms with C
T (P) = compile time + run time
While measuring the time complexity of an algorithm, we concentrate on the frequency count of
all key statements (important statement).
Let us consider three algorithms.
Algorithm
a = a + 1
In this algorithm, the frequency count of key statement a = a + 1, is one.
Algorithm
For I = 1 to n
a = a + 1
[End of loop]
In this algorithm, the frequency count of key statement a = a + 1, is n.
Algorithm
For I = 1 to n
For J = 1 to n
a = a + 1
[End of loop]
[End loop]
In this algorithm, the frequency count of key statement a = a + 1, is n2.
In the first algorithm the statement ― a = a + 1‖ is executed only once, in the second algorithm, ―
a=
a + 1‖ is executed n times and in the third algorithm, ― a = a + 1‖ is executed n2 times.
If an algorithm performs f (n) basic operations when the size of input is n, then its total running
time will be t × f (n), where t is the time required to perform a basic operation.
Note: Different operations consume different times to execute, however for simplicity, we are
assuming that each basic operation consumes same time to execute, which is say t in the above case.
There are three types of time complexities, which can be found in the analysis of an algorithm:
1. Best case time complexity
2. Average case time complexity
3. Worst case time complexity
Best-case time complexity
The best-case time complexity of an algorithm is a measure of the minimum time that the algorithm
will require. For example, the best case for a simple linear search on a list occurs when the desired
element is the first element of the list.
Worst-case time complexity
The worst-case time complexity of an algorithm is a measure of the maximum time that the algorithm
will require. A worst-case estimate is normally computed because it provides an upper bound for all
inputs including the extreme slowest case also. For example, the worst case for a simple linear search
on a list occurs when the desired element is found at the last position of the list or not on the list.
Average-case time complexity
The average-case time complexity of an algorithm is a measure of average time of all instances taken
by an algorithm. Average case analysis does not provide the upper bound and sometimes it is difficult
Analysis of Algorithm | 2.7
to compute.
Average-case time complexity and worst-case time complexity are the most used in algorithm
analysis. Best-case time complexity is rarely found but is does not have any uses.
ASYMPTOTIC NOTATIONS
There are some notations commonly used in performance analysis to characterize the complexity of an
algorithm. Big Oh (O), little oh (o), omega (Ω), theta (Θ) and little omega (ω) are related notations to
describe different kinds of bounds on asymptotic growth rates.
Big O notation introduced in 1894 by Paul Bachmann, popularized in Computer Science by
Donald Knuth, who re-introduced the related Omega and Theta notations.
Big-O (“big oh”) Notation (Upper Bound)
The big-O notation is the formal method of expressing the upper bound of an algorithm's running time.
It is a measure of the longest amount of time it could possibly take for the algorithm to complete. This
notation allows us to compare a function to a set of functions that are bounded by some other function,
allowing us to describe the performance of a particular algorithm.

cg(n)

f(n)

n
no
f(n)=O(g(n))
Figure 2.1: Big-O Notation
If f (n) and g (n) are functions defined for positive integers, then we write f (n) = O (g (n)) if there
exist positive constants n0 and c such that | f (n) | ≤ c | g (n |, for all n ≥ n0.
In general, O (g (n)) = {f (n): there exist positive constants c and n0 such that 0 ≤ f (n) ≤ cg (n) for
all n, where n ≥ n0}.
That is the right of n0, the value of f (n) always lies on or below cg (n). This notation gives an
upper bound for a function to within a constant factor.
Example:
Suppose f (n) = 3n + 2
Now we can write f (n) = 3n + 2 ≤ 4n, for all n≥2, here g (n) = n, c = 4, n0 = 2
Hence, we can write f (n) = O (g (n)) = O (n)
Example:
Suppose f (n) = 10n2 + 4n + 2
Now we can write f (n) = 10n2 + 4n + 2 ≤ 11n2, for all n ≥ 5, here g (n) = n2, c = 11, n0 = 5
Hence, we can write f (n) = O (g (n)) = O (n2)
2.8 | Data Structures and Algorithms with C
Example:
Suppose f (n) = 2n3 + n2 + 2n
Now we can write f (n) = 2n3 + n2 + 2n ≤ 3n3, for all n ≥ 2, here g (n) = n3, c = 3, n0 = 2
Hence, we can write f (n) = O (g (n)) = O (n3)
Big-Ω (Omega) Notation (Lower Bound)
Big-Ω notation is the formal method of expressing the lower bound on an algorithm's running time. It
describes the best that can happen for a given data size. If f (n) and g (n) are functions defined for
positive integers, then we write f (n) = Ω (g (n)) if there exist positive constants n0 and c such that
| f (n) | ≥ c | g (n) |, for all n≥ n0.

f(n)

cg(n)

n
no f(n)=Ω(g(n))
Figure 2.2: Omega Notation
In general, Ω (g (n)) = {f (n): there exist positive constants c and n0 such that 0≤ cg (n) ≤ f (n) for
all n, where n≥ n0}.
That is the right of n0, the value of the function f (n) always lies on or above cg (n). This notation
gives a lower bound for a function to within a constant factor.
Example:
Suppose f (n) = 3n + 2
Now we can write f (n) = 3n + 2 ≥ 3n, for all n ≥ 1, here g (n) = n, c = 3, n0 = 1
Hence, we can write f (n) = Ω (g (n)) = Ω (n)
Example:
Suppose f (n) = 10n2 + 4n + 2
Now we can write f (n) = 10n2 + 4n + 2 ≥ 10n2, for all n≥1, here g (n) = n2 , c = 10, n0 = 5
Hence, we can write f (n) = Ω (g (n)) = Ω (n2)
Example:
Suppose f (n) = 2n3 + n2 + 2n
Now we can write f (n) = 2n3 + n2 + 2n ≥ 2n3, for all n ≥ 1, here c = 2, n0 = 1
Hence, we can write f (n) = Ω (g (n)) = Ω (n3)
Analysis of Algorithm | 2.9
Θ (Theta) -Notation (Tight Bound)
If f (n) & g (n) are functions defined for positive integers, then we say f (n) = Θ (g (n)) if there exists
positive constants n0, c1 and c2 such that
c1 | g (n) |, ≤ | f (n) | ≤ c2 | g (n) |, for all n ≥ n0
In general, Θ (g (n)) = {f (n): there exist positive constants c1, c2 and n0 such that c1 g (n) ≤ f (n) ≤
c2 g (n) for all n, where n≥ n0}.
That is the right of n 0 the value of the function f (n) always lies between c1 g (n) and c2 g (n)
inclusive. This notation bounds a function to within constant factors. This is saying that the function, f
(n) is bounded from both the top and bottom by the same function, g (n).

c2g(n)

f(n)

c1g(n)

n
no
f(n)=Ө(g(n))
Figure 2.3: Theta Notation

Example:
Suppose f (n) = 3n + 2
Now we can write 3n ≤ 3n + 2 ≤ 4n, for all n ≥ 2, here g (n) = n, c1 = 3, c2 = 4, n0 = 1
Hence, we can write f (n) = Θ (g (n)) = Θ (n)
Example:
Suppose f (n) = 10n2 + 4n + 2
Now we can write 10n2 ≤ 10n2 + 4n + 2 ≤ 11n2, for all n ≥ 5
Here g (n) = n2, c1 = 10, c2 = 11, n0 = 5
Hence, we can write f (n) = Θ (g (n)) = Θ (n2)
Example:
Suppose f (n) = 2n3 + n2 + 2n
Now we can write 2n3 ≤ 2n3 + n2 + 2n ≤ 3n3 for all n ≥ 2, here, c1 =2, c2 = 3, n0 = 2
Hence, we can write f (n) = Θ (g (n)) = Θ (n3)
o (“little oh”) - Notation
For non-negative functions, f(n) and g(n), f(n) is little o of g(n) if and only if f(n) = O(g(n)), but f(n) ≠
Θ(g(n)). This is denoted as "f(n) = o(g(n))".
2.10 | Data Structures and Algorithms with C
This represents a loose bounding version of Big O; g(n) bounds from the top, but it does not bound
the bottom. Little-o notation represents a loose bounding version of Big O, g (n) bounds from the top,
but it does not bound the bottom.
If f (n) & g (n) are functions defined for positive integers, then we say f (n) = o (g (n)) iff
f(n)
lim
― =0
n→∞
g(n)

Example:
Suppose f (n) =2n3 + 3n2 + n + 10

Now we can write, lim (2n3 + 3n2 + n + 10)


n→∞ =0
n4
i.e. here g (n) = n4
Hence, we can write f (n) = o (g (n)) = o (n4)
Another definition of little oh (o) is that,
If f (n) & g (n) are functions defined for positive integers, then we say f (n) = o (g (n)) iff
f (n) = O (g (n)) and f (n) ≠ Θ (g (n))
ω (little omega)-Notation
Little-ω notation represents a loose bounding version of Big-Ω; g (n) is a loose lower boundary of the
function f (n); it bounds from the bottom, but not from the top. For non-negative functions, f(n) and
g(n), f(n) is little omega of g(n) if and only if f(n) = Ω(g(n)), but f(n) ≠ Θ(g(n)). This is denoted as
"f(n) = ω(g(n))".
We can write f (n) = ω (g (n)) iff

lim f(n)
― =∞
n→∞
g(n)

Example:
Suppose f (n) = 4n3 + 2n + 3
lim 4n3+2n+3
Now we can write, ――― =∞
n→∞
n2

Here g (n) = n2
Hence we can write f (n) = ω (g (n)) = ω (n2)
Growth Functions of Algorithm
The big-O notation is used to classify algorithms by how they respond in their processing time or
working space requirements to changes in the input size. Order of growth in algorithm means how the
time or space for computation increases with input size, i.e. how the growth function grows with the
input size. Now, based on growth functions, the algorithm can be categorized as follows:
Analysis of Algorithm | 2.11
1. Constant time algorithms [ O(1) ]:
This means that the algorithm requires the same fixed number of steps regardless of the size
of the task.
Example: Array access, Push and pop operations for a stack, enqueue and dequeue operations
for a queue, other atomic operations.
2. Logarithmic time algorithms [ O ( ) ]:
Logarithm time algorithms mean that T(n) is upper bounded by logarithmic of the input size,
i.e. T(n) = .
Example: Binary search in a sorted list of n elements, Insert and Find operations for a binary
search tree with n nodes, Insert and Remove operations for a heap with n nodes, etc.
3. Linear time algorithms [ O (n) ]:
Linear time algorithm means that for large enough input sizes the running time increases
linearly with the size of the input.
Example: Array traversal
4. Linearithmic time algorithm [ O (n ) ]:
An algorithm is said to run in linearithmic time when T(n) = O (n ). Thus, a linearithmic
term grows faster than a linear term, but slower than any polynomial in n with degree greater
than 1.
Example: Merge sort, Heap sort
5. Polynomial time algorithms [O (nk), for k > 1 ]:
i) Quadratic time (O (n2)) algorithm: The number of operations is proportional to the
size of the task squared.
Example: Slow sorting algorithms, for example, selection sort of n elements.
ii) Cubic time (O (n3)) algorithm: The number of operations is proportional to the size
of the task cubed.
Example: Matrix multiplication
6. Exponential time algorithms [ O (kn), for k>1 ]:
Exponential time algorithm means that T(n) is upper bounded by exponential expression of
input size, i.e. T(n) = kn
Example: Towers of Hanoi, implementation of recursive Fibonacci, generating all
permutations of n symbols.
7. Factorial time algorithms [ O (n!) ]:
Polynomial time algorithm means that T (n) is upper bounded by the factorial of the input
size, i.e. T(n) = n!.
Example: Non-attacking n queen problem, traveling salesman problem by brute-force search
The best time in the above list is obviously constant time, and the worst is exponential time,
which, as we have seen, quickly overwhelms even the fastest computers even for relatively small n.
Polynomial growth (linear, quadratic, cubic, etc.) is considered manageable as compared to
2.12 | Data Structures and Algorithms with C
exponential growth.
Table 2.1: Values for different growth functions

n log2n nlog2n n2 n3 2n
1 0 0 1 1 2
2 1 2 4 8 4
4 2 8 16 64 16
8 3 24 64 512 256
16 4 64 256 4096 65536
32 5 160 1024 32768 2147483648
Order of asymptotic behavior of the functions from the above list, we can compare among time
complexities:
O (1) < O ( ) < O (n) < O (nk) < O (kn) < O (n!)

Figure 2.4: Big-O Complexity

Some important points:


 Factorial time algorithms are worst
 Factorial and exponential time algorithms are impractical
 Even polynomial time algorithms of greater than O (n 3) are impractical
 It may be possible to reduce the time complexity significantly by changing the algorithm
design strategy
 For logarithmic time algorithms, if the input is to be read, the total solution may become
linear time.
Many algorithms such as advanced sorting algorithms - quicksort, merge sort, heap sort are of
growth function O (n ), known as linearithmic time; comparisons between O (n ) and other
growth functions
O (n) < O (n ) < O (n2)
Analysis of Algorithm | 2.13
Manipulation of Asymptotic Notations
A number of rules to manipulate asymptotic notations are followed:
Rule 1: O ( c f (n)) = O (f (n))
Rule 2: O (O (f (n)) = O (f (n))
Rule 3: O (f (n) g (n)) = f (n) O (g (n))
Rule 4: O (f (n) O (g (n)) = O (f (n) g (n))
Rule 5: O (f (n) + g (n)) = O (max (f (n), g (n))
Rule 6: If f(n) = O(g(n)) and g(n) = O(h(n)), then f(n) = O(h(n)). [Transitivity Rule]
Rule 7: f(n) = O(g(n)) iff g(n) = Ω(f(n)). [Symmetry Rule]
Suppose, in an algorithm consists of two independent parts-A1 and A2. These parts may be
considered as a sub-algorithm or a single instruction. Let us assume that A1 and A2 take time t1 and t2
respectively for computation.
Now, whenever these two parts are in a sequential structure that means first A1 is computed, and
then A2 is computed, denoted by A1: A2, the total computation time is t1 + t2. According to maximum
rule, the computation time denoted by max (t1, t2).
Example:
Suppose t1 = O (n2) and t2 = O (n), calculate the total computation time for A1:A2
Answer: For A1:A2, computation time = t1 + t2
= max (t1, t2)
= max (O (n2), O (n))
= O (n2)
Again reconsider A1 and A2 are two independent parts of an algorithm, with t1 and t2 as
computation times respectively. Now, whenever these two parts are in a decision structure, that means
A1 is computed only when the given condition is true, otherwise, A2 is computed when the condition is
false, denoted by A1 / A2, the total computation time is t 1 / t2. According to maximum rule, the
computation time denoted by max (t1, t2).
Example:
Suppose t1 = O (n2) and t2 = O (n), calculate the total computation time for A1/A2
Answer: For A1/A2, computation time = t1 / t2
= max (t1, t2)
= max (O (n2), O (n))
= O (n2)
Example:
sum = 0;
for (i=0; i<3; i++)
for (j=0; j<n; j++)
sum++;
Here, the statement sum++ executes 3n times.
Answer: The complexity is O (n)
2.14 | Data Structures and Algorithms with C
Example:
sum = 0;
for (i=0; i<n*n; i++)
sum++;
Here, the statement sum++ executes n2 times.
Answer: The complexity is O (n2)
Example:
sum = 0;
for (i = 0; i < n; i++){
if (is_even(i)) {
for (j = 0; j < n; j++)
sum++;
}
else
sum = sum + n;
}
Here, inside the loop: if ―true‖ clause executed for half the values of n, that is O(n) and if ―
false‖
clause executed for the other half of n, O(1), so innermost loop is O(n). The outer loop is O (n).
Answer: The complexity is O (n2)
Example:
for(i=1;i<=n;i++){
for(j=1;j<=2*i;j++){
k=j;
while(k>=0)
k=k-1;
}
}
At first, consider the innermost while loop: it is executed k = j, j − 1, j − 2. . . 0. Time consumed
inside the while loop is constant. Let I () be the time consumed in the while loop. Thus,
j
I (j) = 1 + 1
k0
Consider the middle for loop, its running time is determined by i. Let M (i) be the time consumed
in the for loop:
2i
M (i) =  I( j)
j 1
2i
=  ( j  1)
j 1
2i 2i
=  j + 1
j1 j 1
Analysis of Algorithm | 2.15

= 2i(2i  1) + 2i
2
= 2i2 + 3i
Finally, the out-most for loop, it is executed i = 1, 2, 3. . . n. Let T (n) be running time of the entire
algorithm:
n
T (n) =  M (i)
i 1
n 2
=  (2i  3i)
i 1
n 2 n
=  2i +  3i
i 1 i 1
3 2
= 2 2n  3n  n + 3 n (n  1)
6 2
3 2
= 4n  15n  11n
6
= O (n3)
Answer: The complexity is O (n3)
Example:
T (n) = 4n2 + 3n , express T (n) in Big-O notation
Ta = 4n2 = O (n2) and
Tb = 3n = O (n )
Now, T (n) = O (max (Ta, Tb))
= O (max (O (n2), O (n )))
= O (n2) [because n > , hence n2 > n ]
Summary
 The algorithm is a finite sequence of instructions/steps, each of which is very elementary that must
be followed to solve a problem.
 The space complexity of a program is the amount of memory it needed to run to completion.
 The time complexity of a program is the amount of computer time needs to run to completion.
 The asymptotic notations commonly used in performance analysis to characterize the complexity
of an algorithm.
 The big-O notation is the formal method of expressing the upper bound of an algorithm's running
time.
Exercises
1. Show that the function f (n) defined by
f (1) = 1
f (n) = f (n-1) + for n > 1
has a time complexity O( ).
2. Define Big-O notation, Θ notation, Ω notations.
2.16 | Data Structures and Algorithms with C
3. The designer of an algorithm needs to balance between space complexity and time complexity.‖-
Comment on the validity of the statement in the context of recursion algorithms.
4. Choose the correct alternatives for the following:
i) Which of the following is the best time for an algorithm?
a) O (n) b) O ( ) c) O (2n) d) O (n )
ii) Which of the following algorithm should execute the slowest for large value of N
a) O (n) b) O (n2) c) O ( ) d) None of these
iii) Let us consider a function f (n) = 1000n + 500 n4 + 0.52n. We can say that f (n) is
a) O (n4) b) O (n ) c) O (2n) d) None of the above
iv) An algorithm is made up of two independent time complexities f(n) and g(n). Then the
complexities of the algorithm is in the order of
a) f(n) ×g(n) b) Max(f(n), g(n)) c) Min(f(n),g(n)) d) f(n) + g(n)
v) Two main measures of the efficiency of an algorithm are
a) complexity and capacity b) Processor and memory
c) Time and space d) Data and space
vi) Which of the following shows the correct relationship between some of the more common
computing time for the algorithm?
a) O ( ) < O (n) < O (n* ) < O (2n) < O (n2)
b) O (n) < O ( ) < O (n* ) < O (2n) < O (n)
c) O (n) < O ( ) < O (n* ) < O (n2) < O (2n)
d) O ( ) < O (n) < O (n* ) < O (n2) < O (2n)

*****
CHAPTER 3

ARRAY AND STRING


"Computers make it easier to do a lot of things, but most of the things they make it easier to do don't
need to be done." -Andy Rooney

M any applications require the processing of multiple data


items, that have common characteristics. For example,
let say we have to find the average marks obtained in a
subject by students of a class. In this case, we have a couple of
KEY FEATURES
 One dimensional array
 Processing an array
choices. Either we can store all the values in different variables or
 Two-dimensional array
we can create an array that will hold all these values in contiguous
memory location. If they are stored in different variables and the  Representation of 2D array
number of such variables is quite large then it is quite  Sparse Matrix
unmanageable as these variables are scattered throughout the
memory. In such situations, it is often convenient to place the data  String
items into an array, where they will all share the same name.
ARRAY
Definition: An array is a collection of the same type of data items, which are stored in consecutive
memory locations under a common name.
An array variable must be followed by square bracket enclosing size specification of the array.
The size signifies the number of elements of the array. That number should be a positive integer
number (greater than 0).
One-dimensional Array
A one-dimensional array is one in which only one subscript is needed to specify a particular element of
the array.
Declaration of One-Dimensional Array
The one-dimensional array can be declared as follows:
data_type array_name [size];
where array_name is the name of an array and size is the number of elements of data type
data_type and size must be an integer constant specified within a pair of square brackets.
Example:
int a[10];
The above declaration states an array, named ― a‖, consisting of ten elements, each of type int.
Simply speaking, an array is a variable that can hold more than one value. (Arrays in programming are
similar to vectors or matrices in mathematics.) We represent the array in above with a picture like this:
3.2 | Data Structures and Algorithms with C

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
a:
Figure 3.1: Array of size 10
Sometimes symbolic constant can be used to define array size rather than an integer number.
Example:
#define N 10
int a[N];
In C, arrays are zero-based, that means the index of an array starts from zero. The ten elements of
a 10-element array are numbered from 0 to 9. The subscript, which specifies a single element of an
array, is simply an integer expression in square brackets. The first element of the array is a[0], the
second element is a[1], etc.
Example:
a[0] = 10;
a[1] = 20;
a[2] = a[0] + a[1];
Notice that the subscripted array references (i.e. expressions such as a[0] and a[1]) can appear on
either side of the assignment operator.
The subscript does not have to be a constant like 0 or 1; it can be any integral expression; it is
common to loop over all elements of an array:
Example:
int i;
for(i = 0; i < 10; i++)
a[i] = 0;
This loop sets 0 to all ten elements of the array a[0] to a[9] .
Arrays are a real convenience for many problems, but there is not a lot that C will do with them
automatically. In particular, you can neither set all elements of an array at once, nor assign one array to
another; both of the assignments are illegal.
Example:
int a[10];
a = 0; /* illegal */
and
int b[10];
b = a; /* illegal*/
To set all of the elements of an array to some value, you must do so one by one, as shown in the
loop example above. To copy the contents of one array to another, you must again do so one by one.
Example:
int b[10];
for(i = 0; i < 10; i++)
b[i] = a[i];
Remember that for an array declared
Array And String | 3.3

int a[10];
there is no element a [10]; the end element is a [9].
Arrays are not limited to type int; you can have arrays of char or float or double or any other type.
Example:
char name[30];
float x[10];
double d[100];
There are some important points about arrays. These are as follows:
 Arrays are always stored in consecutive memory locations.
 An array can store multiple values that can be referenced by a single name.
 An array name is actually an address of the first element of the array.
 An array can be either an integer, character or floating-point data type can be initialized only
during declaration.
 In C, array index starts from zero.
 There is no bound checking concept for arrays in C.
Size of One-Dimensional Array
The one-dimensional array can be declared as:
data_type array_name[size];
The total size of the array in bytes can be calculated by using the following expression:
sizeof(data_type)*size
where data_type is the data type of the array and size specifies the total number of elements of the
array.
Another way to calculate the total size of the array in bytes is simpler; that uses the following
expression
sizeof(array_name)
where array_name is the name of the array.
Initialization of One-Dimensional Array
Although it is not possible to assign values to all elements of an array at once using an assignment
expression, it is possible to initialize some or all elements of an array when the array is defined.
The syntax looks like this:
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
The list of values, enclosed in braces {}, separated by commas, provides the initial values for
successive elements of the array. The individual array elements are as follows:
a[0] = 0
a[1] = 1
a[2] = 2
a[3] = 3
a[4] = 4
a[5] = 5
a[6] = 6
a[7] = 7
3.4 | Data Structures and Algorithms with C
a[8] = 8
a[9] = 9
If there are fewer initializers than elements in the array, the remaining elements are automatically
initialized to 0.
Example:
int a[10] = {0, 1, 2, 3, 4, 5, 6};
would initialize a[7], a[8], and a[9] to 0. When an array definition includes an initializer, the array
dimension may be omitted, and the compiler will infer the dimension from the number of initializers.
For example,
int b[] = {10, 11, 12, 13, 14};
would declare, define, and initialize an array b of 5 elements (i.e. just as if you'd typed int b[5]).
Only the dimension is omitted; the brackets [ ] remain to indicate that b is an array.
Reading array elements
As an array may contain more than one element, so to read all the elements, a single call to the scanf
function will not serve our purpose.
Example:
If we have an array declared as
int a[10];
to read all the elements we can use the following statements:
for(i = 0; i < 10; i++)
scanf (“%d”, &a[i]);
When the value of i is 0 then scanf() will read the value of a[0] element, if i is 1 it will read the
value of a[1] and so on.
Writing array elements
Similarly, to print all the array elements of an array we can use the printf statement within a loop.
Considering the above array declaration int a [10]. We can use the following statements:
Example:
for(i = 0; i < 10; i++)
printf (“%d\t”, a[i]);
Program 3.1: Find out the minimum and maximum of n given numbers.
#include<stdio.h>
main()
{
int a[10], max, min, i, n;
printf(“\nEnter the number of elements:”);
scanf (“%d”,&n);
printf(“\nEnter %d elements:”,n);
for( i = 0 ; i < n; i++ )
scanf(“%d”, &a[i]);
/* Initialization */
Array And String | 3.5

max = a[0];
min = a[0];
/* Finding Maximum and Minimum element */
for(i = 0; i < n; i++) {
if(a[i] > max) max = a[i];
if(a[i] < min) min = a[i];
}
printf (“\n The maximum element is: %d”, max);
printf (“\n The minimum element is: %d”, min);
}
Output:
Enter the number of elements: 5
Enter 5 elements: 3 2 9 5 4
The maximum element is: 9
The minimum element is: 2

Address Calculation in One Dimensional Array


The address of a particular element in a one–dimensional array is given by the relation:
Address of element a[i] = B + W × i
Where B is the base address of the array and W is the size of each element in the array.
Example:
Consider the following array declaration,
int a[10];
Let the size of the elements stored in the above array be 4 bytes each. If the base address of the
array is 1000, then the address of a [5] will be 1000 + (4 × 5) = 1020.
Multi-Dimensional Arrays
Multi–dimensional array is nothing but Array of Arrays. In fact, a two-dimensional array is an array of
one-dimensional array. A three-dimensional array is an array of two-dimensional arrays. Similarly, any
d dimensional array is an array of (d-1) dimensional arrays.
Generally, when we talk about multi-dimensional arrays, we generally talk of two-dimensional
arrays. Since more than two-dimensional is rarely needed.
` There is a need to store and manipulate two-dimensional data structure such as matrices and
tables.
A two-dimensional array is one in which two subscript specifications are needed to specify a
particular element of the array.
Here the array has two subscripts. One subscript denotes the row and the other the column.
Declaration of Two-Dimensional Array
The declaration of two-dimensional arrays is as follows:
data_type array_name [row_size][column_size];
Example:
int m[2][3];
3.6 | Data Structures and Algorithms with C
Here m is declared as a matrix having 2 rows (numbered from 0 to 1) and 3 columns (numbered 0
through 2). The first element of the matrix is m [0][0] and the last row last column is m[1][2].
The two-dimensional array m[2][3] is shown in figure 3.2. The first element of this array denoted
by m [0][0] and the second element is denoted by m [0][1] and so on.
[0] [1] [2]

[0] m[0][0] m[0][1] m[0][2]

[1] m[1][0] m[1][1] m[1][2]

Figure 3.2: Two-dimensional array m [2][3]

Address Calculation in two-dimensional Array


A two-dimensional array can be implemented in a programming language in two ways:
 Row-major Implementation
 Column–Major Implementation
Note: In C language a two Dimensional Array is implemented only by row major order.
Row-major Implementation
In a row-major implementation, memory allocation is done row by row; i.e. all the elements of the first
row is stored then the second row is stored and so on.
[0] [1] [2]

[0] A[0][0] A[0][1] A[0][2]

[1] A[1][0] A[1][1] A[1][2]

[2] A[2][0] A[2][1] A[2][2]

A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2] A[2][0] A[2][1] A[2][2]


row1 row2 row3
Figure 3.3: Two- dimensional array and row-major representation
The two-dimensional array can be implanted in row major order like the above figure 3.3.
Address of element A[i][j] = B + W(n(i – Lr) + (j – Lc))
Where B is the base address of the array
W is the size of each array element
Lr is the lower bound of row
Lc is the lower bound of column
Ur is the upper bound of row.
Uc is the upper bound of column
n is the number of columns , n = ( Uc – Lc ) + 1
Array And String | 3.7
Column-major Implementation
In a column-major implementation, memory allocation is done column by column; i.e. all the elements
of the first column are stored then the second column is stored and so on.
[0] [1] [2]

[0] A[0][0] A[0][1] A[0][2]

[1] A[1][0] A[1][1] A[1][2]

[2] A[2][0] A[2][1] A[2][2]

A[0][0] A[1][0] A[2][0] A[0][1] A[1][1] A[2][1] A[0][2] A[1][2] A[2][2]


column1 column2 column3
Figure 3.4: Two-dimensional array and column-major representation
The two-dimensional array can be implanted in column-major order like the above figure 3.4.
Address of element A[i][j] = B + W((i - Lr)+ m(j – Lc))
Where B is the base address of the array
W is the size of each array element
Lr is the lower bound of row
Lc is the lower bound of column
Ur is the upper bound of row.
Uc is the upper bound of column
m is the number of rows, m = ( Ur – Lr ) +1
Example:
Let the size of the elements stored in an 8 × 3 matrix be 4 bytes each. If the base address of the matrix
is 3500, then find the address of A [5][2] for both row major and column major cases.
Answer: As the lower bounds of row and column are not given, they are assumed as 0. [As in C lower
bounds are always 0]
So, Lr = 0
Lc = 0
Number of rows m = 8
Number of columns n = 3
Size of each element W = 4
Base address B = 3500
So, in row major order address of element A[5][2]
= 3500 + 4 × ((5 – 0) × 3 + (2 – 0))
= 3568
And in column major order address of element A[5][2]
= 3500 + 4 × ((5 – 0) + (2 – 0) × 8)
= 3584
3.8 | Data Structures and Algorithms with C

Initialization of two-dimensional Arrays


Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces.
Example:
int matrix[2][3] = {1, 1, 1, 2, 2, 2};
Initializes all the elements of first row to 1 and the second row to 2. The individual array elements
are as follow:
matrix [0][0] = 1 matrix [0][1] = 1 matrix[0][2] = 1
matrix [1][0] = 2 matrix [1][1] = 2 matrix[1][2] = 2
The initialization is done row by row. The above statement can be equivalently written as
int matrix[2][3] = {{1, 1, 1}, {2, 2, 2}};
When a two dimensional array is completely initialized with all the elements then there is no
explicit need of specifying the first dimensional. That is the statement
Example:
int matrix[][3] = {{1, 1, 1}, {2, 2, 2}}; /* valid */
The compiler will automatically supply the first dimension. However, we have to specify the
second dimension.
So the statement
int matrix[2][] = {{1, 1, 1},{2, 2, 2}}; /* invalid */
is invalid , also the statement
int matrix[][]={{1, 1, 1}, {2, 2, 2}}; /* invalid */
is invalid as the second dimension is missing.
If some of the elements are missing, they are automatically initialized to zero by the compiler. So
consider the following case
int matrix[2][3] = {{1,1},{2,2}};
matrix[0][0] = 1 matrix[0][1] = 1 matrix[0][2] = 0
matrix[1][0] = 2 matrix[1][1] = 2 matrix[1][2] = 0
Here the element matrix[0][2] and matrix[[1][2] are initialized to zero.
Now consider the following case
int matrix[2][3] = {1, 1, 2, 2};
The first four elements are initialized to 1, 1, 2 and 2 respectively and the remaining elements are
initialized to 0 by default by the compiler. Therefore, the matrix elements are
matrix[0][0] = 1 matrix[0][1] = 1 matrix[0][2] = 2
matrix[1][0] = 2 matrix[1][1] = 0 matrix[1][2] = 0
Reading and Writing a two-dimensional array
We have already discussed how to read and write a one-dimensional array. Since there is only one
subscript specification, it requires only one running variable; hence, we can use a single loop.
However, in the case of the two-dimensional array, there are two subscripts. So it requires two
running variables, one for a row and other for a column. Therefore, we have to use nested loops. Now
consider the following example.
Other documents randomly have
different content
“Certainly not. They’re a pair of high class European crooks named
du Val.”
Dorothy shuddered. “And murderers!”
“Undoubtedly. They’re wanted both in England and in Austria for
their crimes.”
“How did you find that out?”
“Oh, you see I recognized them when I arrived here, Miss Dixon.”
“But—but I can’t see why—why you didn’t arrest them then and
there! You knew that they were after the secret of Doctor Winn’s
new explosive, or whatever it is he has invented.”
“Yes, we realized that the formula for Doctor Winn’s explosive gas
was the magnet that drew the du Vals to this house; but until today
we had no idea how they proposed to dispose of the formula after
stealing it.”
“I see. And now you realize that they probably intend to sell it to the
organization of which my uncle is a member?”
“You are right, Miss Dixon.”
“Then why can’t you arrest the Lawsons now?”
“We can take the Lawsons at any time,” Tunbridge explained. “But
we want to catch the ringleader of this organization. We know the
group exists and for no good purpose, but what their definite object
may be we still have no means of telling. We can’t arrest them on
suspicion alone. Once they actually buy the formula from the
Lawsons, it will be quite a different matter.”
She shook her head slowly. “But why hasn’t the formula been stolen
before this? They’ve had plenty of opportunity, surely—”
“Because it is not completed. At dinner tonight I heard the Doctor
say that by tomorrow afternoon the work would be finished, and
that he expected to take the formula to Washington the day after
tomorrow.”
“Then you expect?—”
“I expect that the Lawsons will make their attempt tomorrow night.”
“And where do I come in on this business, Mr. Tunbridge?”
“You are going to take the plans from Doctor Winn’s safe before the
Lawsons get to it.”
She drew her breath sharply. “That’s a pretty large order—”
“I know it, but—of course you’ll have the combination of the safe—”
“Are you going to give it to me now?”
“Too dangerous. They are quite capable of searching your
belongings again—or your person, for that matter—at any time. I’ll
get it to you with exact instructions just as soon as the Doctor
completes that blooming formula and locks it in the safe.”
“That’s all very well, Mr. Tunbridge. But has it occurred to you that if
I steal this paper—I suppose it will be a paper?—”
“Probably several of them—”
“Well, if I take these papers before the Lawsons can get them, how
are you going to arrest my uncle and the other men?”
“You,” directed Tunbridge, “will simply make a copy and replace the
original documents where you found them. This is a safety-first
move. We must have a copy in case the originals are destroyed.”
“It looks like a very complicated matter to me,” Dorothy admitted
candidly. “Why not put the old gentleman wise? After all, it’s his
formula, and if he made his own copy it would save us a possible
run-in with the Lawsons, and—”
Mr. Tunbridge stood up. “Perhaps you’re right,” he said, making a
brave attempt to stifle a yawn, “but Doctor Winn would never agree
to it. For a scientist who dabbles in high explosives, he’s the most
nervous man I’ve ever met. He’d give the whole show away. No,
that’s out of the question. Doctor Winn must be kept in ignorance of
the whole proceeding. And now—” a yawn got the better of him this
time— “and now to bed. You need sleep even more than advice just
now. Good night, or rather, good morning, Miss Dixon. Pleasant
dreams, I hope.”
He started toward the door and Dorothy sprang out of bed and
reached for her dressing gown.
“I want to see that secret passage, Mr. Tunbridge,” she said in a low
tone.
“Oh, yes, come along.” He opened the door and stepped inside the
closet. “It works this way. Press your foot on the board in the
farthest right hand corner, like this, and a panel in the back wall
slides up—like that—”
Dorothy stared at the gaping black hole, then as the detective-butler
snapped on his flashlight she saw that a narrow circular staircase led
downward in the wall.
“That stair curves down to the ground floor,” he explained. “It comes
out through the side wall inside the big fireplace in the hall. To open
the panel down there you press a button under the left-hand corner
of the mantel. To close either panel you simply put it down, once
you’re inside.”
“Are there any more of these passages in the walls?”
“Very likely, but I haven’t found them yet. Winncote is an exact copy
of the Doctor’s ancestral home in Wales. Those old houses were
honeycombed with priest holes, secret passages and whatnot. And
Doctor Winn had his architect copy the original Winncote across the
water down to the last stone, with modern improvements such as
bathrooms and steam heat, added.”
“Funny old fellow, isn’t he?” commented Dorothy sleepily. “Then I’m
simply to carry on until I hear from you again?”
“That’s right. But whatever you do, watch your step with the Lawson
woman. She is fully as heartless as she is beautiful. If you had never
heard of that meeting in the Jordans’ flat, it would be much better
for you. She will try to trap you, so please be on your guard
continually. Well, good night, again.”
“Good night, Mr. Tunbridge.”
The panel in the back wall of the closet slid into place, and Dorothy
went back to bed. She realized now that this matter of
impersonating her cousin was not going to prove to be the easy job
she had fancied. A slip on her part now would not only put her own
life in danger, it would probably ruin all government plans to
apprehend these desperate criminals.
At last she fell into a troubled sleep wherein she dreamed that a long
circular staircase curved round and round her bedroom, and that
Mrs. Lawson, dressed as a butler, had set her to watch every step of
it.
Chapter XI

GRETCHEN

Dorothy awoke from troubled dreams to find that it was another day.
Through the open window she saw the swirl of snowflakes driven in
a high wind. The bedroom was cold and in the grey light of the
winter morning it had lost its cheerful air.
She heard a knock on the door.
“Who’s there?” she called drowsily.
“It’s the maid, miss. Mrs. Lawson thought you might be wanting
your breakfast now.”
Dorothy looked at her wrist watch. The hands marked ten-thirty. She
jumped out on the rug, which felt cold and clammy under her bare
feet, went to the door and unlocked it. Then she scampered back to
bed and snuggled under the warm covers.
In walked a trim little figure wearing the small white apron and gray
uniform of a chambermaid. Dorothy saw a round merry face, and a
pair of big blue eyes beneath the white lawn cap, and thick flaxen
braids were coiled round the neat head. She was surprised and
somehow pleased to discover that this attractive member of the
household staff could not be much more than sixteen, just her own
age.
The little maid shut the door softly, crossed to the window and
closed it, turned on the steam heat and came to the bedside. “Good
morning, Miss Jordan.” She smiled engagingly. “I’m Gretchen, miss.
Will you have your breakfast in bed?”
“Why, thank you, Gretchen—that will be cozy. But if it’s going to give
you any trouble, don’t bother.” With the covers drawn up to her
eyes, Dorothy smiled back at the girl.
“Oh, no, miss—it’s no trouble at all.” Gretchen was insistent. “It’s all
ready now. I’ll run down and bring it up.”
She whisked out of the room and Dorothy rolled over for another
cat-nap.
“If you’ll be good enough to sit up now, Miss Jordan—I have your
breakfast here.”
Dorothy awoke again, yawned and stretched luxuriously. Gretchen
stood beside her bed with the breakfast tray.
“If you’ll be good enough to sit up, miss?” she repeated.
Dorothy punched the pillows into position behind her, slipped the
quilted gown about her shoulders and leaned back. Gretchen moved
nearer—then almost dropped the tray.
“Why—why—miss—”
Dorothy leaned over and steadied the tray. “What’s the matter,
Gretchen?” The little maid was staring at her open-mouthed, her big
blue eyes as round as saucers.
“Oh, I—I beg your pardon, but it’s—it’s the resemblance, miss—Miss
Jordan.” She set the tray over Dorothy’s knees and drew back still
with that astonished look. “I couldn’t see you very well before, miss,
with the covers up to your eyes. But when you sat up, it sure did
give me a start.”
“What do you mean, Gretchen? The resemblance to whom?”
Dorothy, outwardly calm, fingered her glass of orange juice, but her
thoughts raced toward this new complication.
“Why, you look so much like Dorothy Dixon—the flyer, you know,
miss. She’s my hero—I mean, heroine, Miss Jordan. I’ve read
everything the newspapers printed about her and Bill Bolton. You
must have read about them too, everybody has?”
“Oh, yes, I’ve heard about them.” Dorothy hoped her tone sounded
indifferent. “But you know, Gretchen, newspaper pictures are often
very poor likenesses.”
The girl smiled and nodded. “I know that, Miss Jordan. I’ve got them
all and there isn’t no two of the pictures that looks alike.”
“Then how—?”
“You see, it wasn’t the newspaper pictures I was thinking of, miss,
but Dorothy Dixon herself. You see I know Miss Dixon,” she went on
proudly, “and you two are certainly the spittin’ images of each other,
if you don’t mind my saying so.”
Dorothy minded very much, but it was not consistent with the part
she was playing to admit it. Here was a contretemps not even
Ashton Sanborn had foreseen. Yet, of course, New Canaan was only
ten miles away. She had many friends in Ridgefield, and she’d been
there hundreds of times. But she simply couldn’t remember having
seen Gretchen in any of their homes. Her answer was but a feeble
stall for time.
“So you know her then?” she said lamely.
“Oh, yes, miss. Not well, you understand. I saw her and Mr. Bill
Bolton first when they finished the endurance test on the Conway
motor this fall. Then a few days later, I drove over to her house in
our flivver—over to New Canaan, you know, and I called on Miss
Dixon. I wanted her to autograph a picture of herself I’d cut out of
the Sunday paper.”
“And you met her?” Dorothy remembered the incident perfectly now.
But the maid’s uniform—and her hair—when she had seen her,
Gretchen had worn two braids over her shoulders, very much the
schoolgirl. No wonder she hadn’t recognized her. But now what
should she do? Would it be possible to keep up this camouflage with
a girl whom she had met and with whom she would come in daily
contact? Gretchen was talking again.
“Yes indeed, I met her. And she was just darling to me, Miss Jordan.
She even gave me one of her own photographs and wrote on it, too.
You see, us Schmidts came over from Germany about a hundred
years ago, but we’re honest-to-goodness Americans just the same.
Father was in the American army during the war. He was an aviation
mechanic. He found one of them Iron Crosses of the Germans on
some battlefield in France and kept it for a mascot. And would you
believe it, miss, Father never even got wounded once, the whole
time he was over there! Perhaps it was the little Iron Cross, and
perhaps it wasn’t. Anyway, he thought a lot of his mascot. When I
was ten years old, he had it fixed on a thin gold chain for me to
wear around my neck, and gave it to me on my birthday. Well, when
I went to see Miss Dixon this fall, I took it with me. She goes up in
her airplane so much and does so many other exciting things, I
wanted her to have it. She didn’t want to take the cross at first, but
I persuaded her to, just the same. And you don’t know how nice she
was to me, Miss! Took me out to see Will-o-the-Wisp—that’s her
plane, you know—she calls it Wispy for short. And I had a perfectly
grand time. She’s my heroine, all right. And you, miss—I hope you’ll
excuse me for talking so much about it—but you look exactly like
her, and your voices are just the same, too. It’s wonderful!”
“So you are Margaret Schmidt,” Dorothy said slowly.
“Yes, miss, that is so, though everybody calls me Gretchen. How did
you know my given name, Miss Jordan? Is Miss Dixon a friend of
yours? Did she tell you about me? But that’s silly—she wouldn’t
remember me.”
Dorothy looked the little maid straight in the eyes. “She remembers
you, Gretchen. Would you be willing to do something for her—to
keep a secret, a very important and maybe a dangerous one? Do
you think you could do it?”
Gretchen looked awestruck, then she smiled. “Mother says I’m the
closest-mouthed girl she ever saw, miss. They could cut me in pieces
before I ever let out any secret of Dorothy Dixon’s. I’d never tell—
not me! You can trust me, Miss Jordan.”
“I’m sure I can, Gretchen. And I’m going to.” Dorothy slipped her
hand into the V-neck of her pajamas. “Remember this?”
“Why—it’s—it’s my Iron Cross—that I gave Dorothy Dixon. How in
the world—?”
“I am Dorothy Dixon.” Dorothy broke into laughter at the bewildered
expression on the girl’s face.
“But—but I don’t understand!” Gretchen stammered as though her
tongue was half-paralyzed. “I knew the resemblance was wonderful
—but—they said you were Miss Janet Jordan—and—”
“You sit down on the end of the bed,” said Dorothy, “I’ll go on with
my breakfast before it gets cold, and explain at the same time. We
won’t be disturbed, will we?”
“Oh, no, miss.”
“How about your work, Gretchen? Will you be wanted downstairs?”
“Mr. Tunbridge told me to unpack your trunk, miss—Miss Dixon—and
to make myself generally useful.”
“Fine,” smiled Dorothy, pouring out a cup of coffee. “But keep on
calling me Miss Jordan—otherwise you’ll be making slips in the name
in front of other people and that would be fatal.”
“Yes, Miss Jordan,” Gretchen grinned happily.
“After this beastly business is over,” Dorothy went on, “we’ll be
Gretchen and Dorothy to each other.”
The other girl looked a trifle embarrassed. “But I’m only a
chambermaid, Miss Jordan,” she said shyly.
“Don’t be silly!” Dorothy waved away the argument with a sweep of
her spoon. “You’re proving yourself a real friend—and that’s that.”
“Very well, Miss Jordan.”
“Now pin back your ears, Gretchen.” Dorothy lifted the cover from
her scrambled eggs. “I am taking my cousin, Janet Jordan’s place as
Mrs. Lawson’s secretary. Nobody in this house knows who I am
except Mr. Tunbridge, nor must they be given the slightest hint that I
am anybody but Janet Jordan. As you’ve probably guessed, Janet
and I look almost exactly alike. Our mothers were twins and that
probably accounts for it.”
“Gee—” breathed Gretchen. “It’s just like a story in a book!”
Dorothy bit into a slice of buttered toast. “Maybe it is,” she admitted,
speaking with her mouth full. “But the point is that you and I are
living this story and it may come to a very abrupt and unpleasant
ending unless we’re both terribly careful. Let’s see—where was I?
Oh, yes. Mr. Tunbridge and I are working together on this case,
working for the United States Government.”
“Secret Service?” asked Gretchen in an awed whisper.
“Yes.”
“Then I’ll be working for the secret service too?” Dorothy could see
that the girl was very much impressed with the idea.
“You will, Gretchen—that is, you are—under me. But don’t get too
pepped up about it. The work we are on is serious and it is
extremely dangerous into the bargain. I wouldn’t have brought you
into it unless I had to. Right now I haven’t the slightest notion how
you are going to be fitted into the picture. But I couldn’t have you
going around, talking about how much Janet Jordan looks like
Dorothy Dixon, could I? Doctor Winn and the Lawsons have no idea
of either the resemblance or the relationship. If that came out and
they got wind of it—well, there’s no telling what might happen.”
“Especially,” chimed in Gretchen, “after all the detective work you did
in those three big cases over to New Canaan this summer and fall.”
“You’ve got it,” declared Dorothy, and sipped her coffee. “A robbery
is being planned here, Gretchen, a robbery of some very valuable
papers from Doctor Winn’s safe. The thieves will probably try to pull
it off tonight. These papers, which have to do with an invention of
the Doctor’s are worth a million dollars or more to any number of
people. So you see the thieves are playing for big stakes, and I
might as well tell you that they aren’t the kind that would let a thing
like murder stop them. And now that you know the facts, are you
willing to go on with it?”
Gretchen seemed horrified that Dorothy should doubt her. “Oh, Miss
Jordan, I don’t want to get murdered any more than anybody else—
but, I’m not afraid—honest I’m not!”
“I knew you were true blue,” smiled Dorothy. “So we’ll call it a deal,
shall we?”
“You bet!” The two girls solemnly shook hands. “What do you want
me to do first, Miss Jordan?” Gretchen asked eagerly.
“Move this tray onto the chair over there, please. Then while I’m
taking a bath and dressing you might unpack Janet Jordan’s clothes.
I’ll choose something to wear later.”
“Very good, Miss Jordan.” The little maid took the tray, then stopped
short, her round blue eyes very serious. “But what about the secret
service work?”
“Just carry on as usual for the present.” Dorothy slipped out of bed.
“And remember—not a word to anyone about what I’ve told you—
not even Mr. Tunbridge. I don’t know myself exactly what I’m to do
yet. Mrs. Lawson expects me downstairs in about half an hour, so
I’ve got to hustle. If I need your help later on, I’ll get word to you
somehow.”
“I hope you will need me, Miss Jordan.” Gretchen was taking Janet’s
frocks from the wardrobe trunk.
“And I hope I shan’t!” said Dorothy, and she disappeared into the
bathroom.
Chapter XII

TESTS

Dorothy came down the wide staircase a few minutes before eleven-
thirty. She wore a dark blue morning frock of her cousin’s, its
simplicity relieved only by the soft white collar and deep cuffs.
Except for being rather tight across the shoulders it fitted her as
though she had been poured into it. She had selected this dress
because she knew it was just the sort of thing a new secretary
would be expected to wear.
She crossed the broad hall to the open door of the library, and there
found Mrs. Lawson standing before a window staring into the storm.
Although Dorothy’s footsteps made practically no sound on the thick
pile of the handsome Bokhara rug, the woman turned like a flash at
her entrance.
“Oh, good morning, Janet.” The frown on her face gave way to a
pleasant smile. “I hope you were comfortable last night. Did you
sleep well?”
“I dropped off as soon as my head touched the pillow,” she
answered, taking Mrs. Lawson’s outstretched hand. Dorothy did not
believe in telling a lie unless it was in a good cause; but when
necessary, she invariably made the lie a good one.
“I hope the storm didn’t wake you,” smiled Laura, holding Dorothy’s
hand.
Dorothy did not reply at once. Two long fingers were lightly pressing
her wrist, and she saw that Mrs. Lawson’s eyes had strayed to the
grandfather’s clock in the corner of the room. “Test number one,”
she said to herself. “Mrs. du Val, alias Lawson is counting my pulse.
Well, I’ve got a clear conscience, perhaps I can give her a shock.”
She drew her hand away and answered the woman’s question in her
normal voice. “Oh, the storm! No, I never heard it, Mrs. Lawson. If
that hot lemonade had been drugged, I couldn’t have slept any
sounder!”
“What makes you say that?” snapped her employer, and beneath the
velvet tone, Dorothy sensed the ring of steel.
She dropped her eyes, and turning toward the open hearth, held out
her hands to the crackling blaze. “Oh, I don’t know,” she said
sweetly and like the clever little strategist that she was, opened her
own offensive in the enemy’s territory. “I have the bad habit of
occasionally walking in my sleep, Mrs. Lawson—and especially when
I spend the night in a strange bed. Perhaps it’s nervousness—I don’t
know.”
Mrs. Lawson threw her a sharp glance. “Sit down, Janet,” she
suggested, pointing to a chair near the fire, and taking one herself
across the hearth. “You’re—I mean, you don’t seem to be at all
nervous this morning.”
“Good old pulse!” thought Dorothy. Then aloud—“No, I feel
splendidly, thank you. But, you see, I didn’t walk in my sleep last
night.”
“But surely you can’t tell when you do it!”
“Oh, yes, I can.” Dorothy’s manner and tone were those of the
simple schoolgirl proud of an unusual accomplishment.
“You don’t expect me to believe that you know what you’re doing
when you walk in your sleep, Janet. That’s impossible!”
“Not while I’m sleepwalking, Mrs. Lawson. That wasn’t what I said—
but when I have been sleepwalking—there’s a difference, you see?”
“Well?” The lady of the house objected to being contradicted and
took no trouble to hide it.
“It’s really very simple,” explained Dorothy, painstakingly, as though
she were speaking to a rather stupid child. “I found out how to do it.
You see, I’ve been walking in my sleep ever since I was a little thing.
When I get in bed at night I leave my slippers on the floor beside it
pointed outward—away from the bed. We all leave them that way, I
guess. It’s the natural thing to do.”
“But what have slippers got to do with it?” Laura was becoming
impatient.
“Everything, so far as I’m concerned, Mrs. Lawson. When I’ve been
walking at night, I always find them in the morning beside the bed,
but pointing toward it. I evidently slip them off before I get back into
bed, and—”
“I’m beginning to think you are quite a clever girl, Janet.”
“Oh, thank you,” said Dorothy with a guilelessness that was sheer
camouflage. “Has anybody been saying I’m stupid? I’ve always stood
high in my classes at school.”
“Oh, not stupid, child—but nervous—perhaps a little unbalanced,
especially this past week.”
Dorothy raised her heavy lashes and looked Mrs. Lawson squarely in
the face. This might be a test she was undergoing and it probably
was; but here was a heaven sent chance to stir up discord in the
enemy’s camp. She must work up to it gradually.
“I know that I was nervous and upset past all endurance.” She
leaned forward, her hands on the arms of the chair. “How would you
like your father to lock you in your bedroom for a week, without ever
coming to see you, or giving you any explanation for such
outrageous treatment? Am I a child to be handled like that? To be
shipped up here to strangers, whether I wanted to go or not? How
would you feel about it, Mrs. Lawson, if you were me? Don’t say you
would submit to it sitting down.”
“But I am taking you on as my secretary,” the lady hedged. “Offering
you a good position for which you’ll be paid twenty dollars a week.
That’s not to be thought of lightly, especially in these times.”
“But it doesn’t seem to strike you that I might like to have
something to say about it,” Dorothy replied calmly. “As for the salary
—that’s no inducement. My mother left me five thousand a year. I
came into the income on my last birthday, so you see I have nearly a
hundred dollars a week, whether I work or not.”
“I didn’t know that, of course,” Mrs. Lawson admitted and none too
graciously. “Your father wants you to be here while he’s away. I hope
you aren’t going to be difficult, Janet.”
“I hope not, Mrs. Lawson. I shall be glad to stay here for a while and
do the work you’d planned for me; but if I do, it must be as a guest
and not as a paid dependant.”
“But you are a guest, Janet.”
“I shall not accept a salary, Mrs. Lawson.”
“Very well, my dear, if you wish it that way.”
“Thank you very much.”
“To get back to our former topic,” Mrs. Lawson said, and lit a
cigarette. “I can understand that your father’s conduct in confining
you to your room might be exasperating—but why should it make
you nervous? And my husband tells me that when he visited you in
your room you acted as though you were in deadly fear of
something or somebody every time he saw you. What was the
trouble, Janet? Was anything worrying you?”
“Yes, there was, Mrs. Lawson.”
Dorothy looked down at the andirons, and her hands on the chair
arms twisted embarrassedly. From the corner of her eye she saw a
smile of satisfaction light up the older woman’s face. She knew she
was playing with fire and that Mrs. Lawson was watching her as a
hawk watches its defenseless prey before it strikes. But all unknown
to her inquisitor, Dorothy had been leading her into this trap as a
move forward in her own game. Genuine dislike for the woman as
well as a mischievous impulse on her part drew her to make the
scene as dramatic and convincing as possible.
“Yes—I—I—was afraid,” she went on, dragging out the words slowly.
“Then don’t you think you’d better tell me about it, Janet? I’m nearly
old enough to be your mother. Let me take your mother’s place,
dear. Give me your confidence. I feel sure I’ll be able to help you,
child.”
This reference to Janet’s dead mother by a woman who was the
vilest kind of a hypocrite swept away Dorothy’s last compunction.
She herself was going to commit justifiable libel. Mrs. Lawson, on
the other hand, was attempting to lead Janet Jordan into a
confession of shamming sleep at the fateful meeting a week ago.
And such a confession meant a sentence of death from this beautiful
siren who gazed at her so winningly, who puffed a cigarette so
nonchalantly while she waited for an unsuspecting girl to commit
herself.
“Well, I don’t know—I can’t help hesitating to tell you, Mrs. Lawson,”
Dorothy began timidly.
“There’s no need to be afraid of anything,” replied the woman, only
half veiling the sneer that went with the words.
“Oh, but you see, there is, Mrs. Lawson!” Dorothy’s manner was still
indecisive. “I don’t want—in fact, I hate awfully to hurt you this
way.”
“Hurt me!” Mrs. Lawson’s cigarette snapped into the fireplace like a
miniature comet. “Hurt me, child? What in the wide world are you
talking about?”
“Just what I say, Mrs. Lawson.”
Mrs. Lawson sniffed. “Don’t be ridiculous, Janet. Out with it now.
What did you fear when you were locked in your room?”
“Your husband, Mrs. Lawson.”
“My husband!”
“Yes.”
“But—why—I don’t believe you.”
“Oh, very well. You asked the question, I was trying to answer it,
that’s all.”
Mrs. Lawson bit her lip. She was furious. “As long as you’ve said
what you have, you’d better go on with it,” she said acidly.
“There isn’t any more,” returned Dorothy. “That’s all there is.”
“But surely he must have given you reasons for your assertion.” Mrs.
Lawson had walked beautifully into Dorothy’s trap. Her own plan to
snare an unsuspecting girl had been blotted out by the shadow of
the Green Goddess, Jealousy. “Tell me what my husband did or said
to make you fear him, and tell me at once.”
“It wasn’t what he did, Mrs. Lawson—it was the way he looked.”
“What do you mean—the way he looked?”
Dorothy had thrust a painful knife into the mental cosmos of her
adversary. Now she deliberately turned it in the wound. “Very
probably,” she said quietly, looking her straight in the eyes, “you can
remember how Mr. Lawson looked when he first made love to you. I
don’t want to be made love to, and I don’t like him, Mrs. Lawson.”
“What did you do?”
“I told him to leave me—and when he would not go, I simply walked
into my bathroom and locked the door.”
“But what happened the next time he came? Martin went in to see
you every day, didn’t he?”
“He did. But he talked to me through the bathroom door. Just as
soon as I heard the key turn in the lock I’d hop in there.”
The man she had been talking about must have been listening just
outside in the hall, for now he strode into the room and up to
Dorothy. “That,” he said menacingly, “is a deliberate lie, Miss Janet
Jordan!”
Chapter XIII

WINNITE

Dorothy looked up and smiled carelessly at the man. “You’re very


polite, Mr. Lawson. Perhaps it isn’t my place to say it to a man old
enough to be my father—but eavesdroppers rarely hear good of
themselves.”
Martin Lawson, who prided himself upon his youthful appearance,
grew angrier than ever. “I—I won’t stand for such outrageous libel,”
he thundered. “I’ve always treated you as though you were my own
—well, daughter, if you like.”
“I don’t like it, Mr. Lawson—but that doesn’t make any difference,”
Dorothy’s tone was one of pained acceptance. “If you listened long
enough, you will know that I didn’t bring this matter up myself. Mrs.
Lawson was asking questions and I was trying to answer them,
that’s all. If you prefer it, I’ll say that it was the wind whistling
outside the windows that made me afraid.” She looked over at Mrs.
Lawson, who was watching them through half shut eyes, as though
to say, “—you understand, of course—anything for peace.”
Martin Lawson intercepted the glance and became even more
furious, if that were possible. “You—you little viper!” he snarled.
“Laura, don’t you believe a word of it. The whole thing’s her own
invention—a pack of lies!”
“A silly schoolgirl fancy, if you like, Martin.” Laura Lawson’s tone was
expressionless. “But I can understand it just the same. Yes, I can
understand it.”
“What do you mean—you understand it?”
“I was a girl once myself,” she replied in the same colorless tone.
“And then, you see, I know you very, very well.”
“Oh, you do, do you?”
“He’s off again,” sighed Dorothy, but quite to herself.
“And you have the nerve to insinuate—?” the angry man went on,
beside himself with rage. “You know as well as I do, Laura, that this
girl was afraid because of what she saw and heard at the meeting.
She—”
“That will be quite enough, Martin.” His wife interrupted him sharply.
“And what is more—you probably have not noticed that since Janet
has been here and with other people, she is very much herself—and
afraid of nothing at all.”
“What meeting is he talking about, Mrs. Lawson?” Dorothy pointedly
ignored the angry husband.
Mrs. Lawson stood up. “Never mind that now,” she decreed, albeit
pleasantly. “Come along with me to my office. I have some typing I’d
like you to do for me before luncheon. Martin!” She swung round on
her husband. “You will wait here for me. I’ll be back in a few
minutes—I want to talk to you.” She slipped her arm through
Dorothy’s and drew her from the room.
Once in the entrance hall, she led her back and under the gallery to
a corridor which opened at the right of the broad stairs. Dorothy saw
that there were several doors in the right hand wall. Mrs. Lawson
stopped at the second of these and opened it.
They walked in and Dorothy saw that they were in the office. It
seemed very businesslike and austere after coming from the luxury
of the library and spacious hall. Near the one window stood a broad
table desk, and opposite that a typewriter desk. Two steel filing
cabinets and three plain chairs completed the room’s furnishings.
The walls were hung with framed blueprints and a large-scale map
of Fairfield County, Connecticut.
Mrs. Lawson took some papers from a drawer in the large desk and
handed them to Dorothy. “This is in longhand, as you see,” she
explained, “please type it, double space, and I’d like to have a
carbon copy.” She glanced at a small wrist-watch set with diamonds.
“It is just noon now. Luncheon is at one. Do you think you can finish
the work by that time?”
Dorothy glanced at the manuscript. “This won’t make more than four
typewritten sheets. I can do it easily in an hour and have time to
spare.”
“Good!” The older woman patted her lightly on the shoulder. “Take
your time about it. Do you think you can read my handwriting?”
“Nothing could be plainer, Mrs. Lawson.” Dorothy smiled back at her.
“Very well, then. I’ll see you at lunch. The dining room is across the
hall from the library.”
At the door, she stopped and turned as though she had just
remembered something.
“Don’t let what my husband said bother you, Janet.”
“That’s forgotten already,” Dorothy said easily.
“Like most men, he flies off the handle when irritated. Pay no
attention to it.”
“I understand.”
Mrs. Lawson hesitated for the fraction of a second. “By the way,
Janet,” she remarked. “When was the last time you walked in your
sleep—that you found your slippers pointed toward your bed in the
morning?”
Dorothy pretended to think. “Let me see,” she said slowly. “Yes—it
was the night before Daddy locked me in my room! I found that I
couldn’t get out in the morning, and naturally, I wanted to know the
reason why. I still do, for that matter. Except for some foolishness
about my being ill, I’m still waiting for an explanation. As a matter of
fact, I was perfectly well. I’m terribly annoyed, of course, and it
worries me to think that Daddy should act this way, but so far as my
health goes, I’ve never felt better.”
“I’m glad to hear it, dear. We’ll check up on your father when he
returns. I’m your friend, you know. Don’t let the matter prey on your
mind.”
“Thank you, Mrs. Lawson. I’ll try to do as you say.” Dorothy thought
she was going then, but it seemed that the woman had still another
question that she had been holding back.
“When you are in this somnambulistic state,” she said, “when you
are sleepwalking, I mean, doesn’t it terrify you to awaken and find
yourself out of your bed?”
Dorothy frowned and seemed puzzled. “Perhaps it would,” she
admitted. “But then, you see, I can’t remember ever wakening while
I was walking during the night. I must sleep very soundly. At school
the night watchman or one of the teachers would frequently find me
walking about the building. They would lead me back to bed, or just
tell me to go there, and I would always obey. Until they told me
about it next day, I knew nothing of course. That’s how I got onto
the business of the slippers, you see.”
“Oh, yes. I wondered how you’d been able to check on it. Well, I
must trot along now and let you get to work. Until luncheon then,
my dear.”
She was gone at last and Dorothy made a face at the closed door.
“Of all the plausible hypocrites I’ve ever met,” she muttered, “you
certainly take the well known chocolate cake!”
She sat down at the typewriter desk, pulled out the machine, and
slipped in two sheets of paper and a carbon that she found in one of
the drawers. Halfway through a perusal of Mrs. Lawson’s first page,
she looked up. The door opened quickly and Mr. Tunbridge came
into the room.
“I’ve just a moment,” he prefaced hurriedly. “They mustn’t find me
here. What was the row in the library?”
Dorothy explained briefly.
“Fine! Put you through the hoops, eh? I had a good idea she would
do something of the kind. You came out of a difficult situation with
flying colors, I take it. But be careful about run-ins with Lawson.
He’s a slick article—in fact, the two of them are a pair of the slickest
articles it’s ever been my misfortune to run across. And they’re going
it hammer and tongs in the library right now. I was a bit worried
about you, that’s why I took this chance.”
“When do I get my instructions for tonight?”
“Late this afternoon, probably. I’ll get them to you somehow.”
“Thanks. And here’s something else. This script I’m going to type for
Mrs. L. has to do with the properties of a highly explosive gas which
seems to burn up everything it comes in contact with and lets off
fumes of deadly poison while it’s doing that! Shall I make a copy for
you?”
“Please do!” His hand rested on the doorknob. “Yes, it’s important
that we have a copy. That’s the stuff Doctor Winn has just invented,
without a doubt.”
“Awful!” exclaimed Dorothy. “Just think what would happen if that
were used in a war!”
“That’s the government’s business, Miss Dixon.”
“‘Ours but to do—and die—’” she quoted and her tone was deadly
serious.
“Quite right. But make the carbon copy just the same—and don’t let
them catch you at it.”
“I won’t, Mr. Tunbridge.”
“Bye-bye, then. I’ll get along now. There may be some home truths
floating out of the library that will give me extra dope on the du-Val
—Lawson pair.”
The door closed, and after slipping an extra carbon and a sheet of
very thin copy paper into the typewriter, Dorothy read Mrs. Lawson’s
treatise on “Winnite and Its Properties” from start to finish.
“Horrible!” she murmured, as she finished reading. “Simply horrible!”
Again her eyes sought the last paragraph. “The effect is easily
estimated of an airplane dropping a single bomb filled with the
explosive, inflammable and deadly poison gas, Winnite, upon
Manhattan Island, for instance: the bomb would explode upon
detonation and within an inconceivably short space of time, not only
would the City of Greater New York be in flames, but every living
thing within that area would be dead from the poison fumes. This
includes not only human, animal and insect life, but all vegetable
matter as well.”
Dorothy sighed. “And I am supposed to help keep this terrible stuff
from the hands of thieves so that our government may use it in time
of war. Well—we’ll see—and that’s not that by a long shot!”
She put down the manuscript and began to type it.
Chapter XIV

PROFESSOR

Dorothy, upon finishing the article on Winnite, laid the original and
first carbon copy of the typewritten sheets on Mrs. Lawson’s desk.
The almost transparent sheets of the second carbon copy she folded
carefully as though she meant to place them in an envelope. But
instead of this, her right foot slipped out of its walking pump, the
sheer silk stocking followed it. Then she put on the stocking again,
but now the soft papers rested between the stocking and the sole of
her foot. The pump fitted more snugly than before, although not
uncomfortably so. Content with her morning’s work, she had closed
the typewriter and was studying the effect of a new shade of
powder in her compact mirror when Mrs. Lawson came into the
room.
“I take it you’ve finished the work?”
“The original and copy are beside the longhand manuscript on your
desk,” said Dorothy, toning down her efforts with the puff. “I’ve read
it over and I don’t think you’ll find any mistakes.”
Mrs. Lawson ran her eyes over the typewritten sheets. “They are
without a fault,” she declared, placing them in a drawer. “If you take
dictation as accurately as you type, Janet, you’ll be the perfect
secretary.”
“Thank you,” said Dorothy demurely and slipped the compact into
the pocket of her frock. “It is very nice of you to say that.”
“Then we’ll go in to luncheon, shall we? That is, if you’re ready?”
Dorothy stood up. “Quite ready, Mrs. Lawson, and good and hungry,
too.”
“Splendid!” enthused her hostess, as they walked down the corridor
toward the entrance hall. “Doctor Winn declares this Connecticut
Ridge country is the most healthful section of the United States. And
even if some people have other ideas on the subject, I can testify
that it is a great appetite builder.”
Dorothy smiled, but said nothing. She was wondering how healthful
she was going to find this particular spot in the Ridge country after
what she had to do tonight.
“Doctor Winn always lunches in his study,” continued Mrs. Lawson.
“That is the room just beyond my office. My husband has been
called to New York on business. He won’t be back until after dinner
tonight, so we will be alone at luncheon.”
For some reason of her own, Laura Lawson had become affability
itself. And for this Dorothy gave thanks. That she disliked this truly
beautiful creature was only natural. But it is much more pleasant to
lunch with a person who puts herself out to be charming and
affable, no matter what your private opinion of the other’s character
may be.
The dining room proved to be a low-ceiled apartment paneled in
white pine; heavy beams of the satin-finished wood overhead, and
on the walls several colorful landscapes in oils, evidently the works
of artists who knew and loved this Ridge country. A cheerful log fire
burned brightly on the open hearth beneath a high mantelpiece.
Outside, the heavy snow continued to drive past frosted window-
panes, but within all was warmth and coziness.
Dorothy enjoyed the meal thoroughly. Like most girls, she revelled in
luxury when it came her way. Not only was her hostess an
interesting and entertaining conversationalist, the delicious food
served by Tunbridge and a second man in plum-colored knee
breeches, added materially to her pleasure. She was really sorry
when the butler lighted his mistress’ cigarette and Mrs. Lawson rose
from the table.
“I have no work for you this afternoon, Janet,” said the lady, as they
strolled into the spacious hall with its suits of polished armor and
trophies of war and the chase decorating the walls. “I have some
work to complete with Doctor Winn, so I won’t be free to entertain
you. There are periodicals and novels in the library. If it weren’t such
a beastly day, I would suggest a walk.”
“Oh, I don’t mind a snowstorm!” Dorothy smiled at her. “I’d love to
be out in it for a while.”
“But I’m afraid you might get lost. The blizzard is driving out of the
northeast—and that means something in this country. You’ll find it
more disagreeable than you think.”
“I’m not afraid to walk in a blizzard,” Dorothy argued, “we used to do
it a lot at school—I love it.”
“Oh, very well, then,” went on Mrs. Lawson. “I used to enjoy that
sort of thing myself. Somebody had better go with you, though. Let
me see—” She hesitated. “Oh, yes—Gretchen will be just the person.
She’s a nice little thing—a native of Ridgefield, you know. Gretchen
can show you round the place, and there’ll be no chance of your
getting lost.”
Dorothy was amused by this pretended concern for her safety. She
knew that Mrs. Lawson feared she might take it into her head to
walk to the railroad station and board the first train back to town.
Gretchen as guide and chaperone would be able to forestall anything
like that. Mrs. Lawson was not yet sure of the new secretary!
Dorothy’s features betrayed no sign of her thoughts. “That will be
ever so much pleasanter than going alone,” she agreed. “Gretchen
seems to be a sweet girl. I saw her this morning when she brought
my breakfast and unpacked my clothes. I’m sorry, though, that you
can’t come too.” Deception, she found, was becoming a habit when
treating with her hostess.
“Thank you, my dear—I’m sorry, too.” Mrs. Lawson went toward the
tasselled bell rope that hung beside the fireplace. “Run upstairs now
and get into warm things. I’ll ring for Gretchen and have her meet
you down here in quarter of an hour.”
Fifteen minutes afterward, warmly dressed in whipcord jodhpurs, a
heavy sweater and knee-length leather coat of dark green, Dorothy
came out of her room onto the gallery, pulling a white wool skating
cap well down over her ears. With a white wool scarf twisted about
her throat, the long ends thrown back over her shoulders, she
looked ready for any winter sport as she ran lightly down the stairs,
the rubber soles of her high arctics making no sound on the broad
oaken steps.
Gretchen, well bundled up in sweater and heavy tweed skirt was
waiting for her.
“You certainly do look like a picture on a Christmas magazine cover,
Miss Jordan,” the girl exclaimed, while they walked to the front door.
“I’m glad you’ve got warm gauntlets. It’s mighty cold out—you’ll
need them.”
Dorothy laughed gaily and swung open the door. “Nothing could be
more becoming than your own costume, Gretchen. That light blue
skating set is just the color of your eyes.”
“That,” chuckled Gretchen, “is the real reason I bought it.”
They were outside now and standing under the wide porte-cochere
of glass and wrought iron.
“It’s glorious out here, and not too cold, either.” Dorothy sniffed the
sharp air enthusiastically. “I hate staying indoors on a wild day like
this. Look at those big flakes spinning down and sideslipping into the
drifts. It makes one glad to be alive.”
“You said it, Miss Jordan. I love it myself—though I never thought of
snowflakes being like airplanes before. Which way do you want to
go?”
“You’re the leader, Gretchen. Anywhere you say suits me.”
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

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


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

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


personal growth every day!

ebookbell.com

You might also like