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

Programming In C Volume 1 Basic Data Structures And Program Statements Xingni Zhou pdf download

The document discusses 'Programming in C Volume 1: Basic Data Structures and Program Statements' by Xingni Zhou and others, focusing on teaching programming concepts through problem-solving and debugging techniques. It highlights common challenges faced by students in learning programming and proposes strategies to enhance understanding and skills. The book aims to make programming more accessible by emphasizing logical thinking and the nature of programming problems.

Uploaded by

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

Programming In C Volume 1 Basic Data Structures And Program Statements Xingni Zhou pdf download

The document discusses 'Programming in C Volume 1: Basic Data Structures and Program Statements' by Xingni Zhou and others, focusing on teaching programming concepts through problem-solving and debugging techniques. It highlights common challenges faced by students in learning programming and proposes strategies to enhance understanding and skills. The book aims to make programming more accessible by emphasizing logical thinking and the nature of programming problems.

Uploaded by

sghramai
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/ 76

Programming In C Volume 1 Basic Data Structures

And Program Statements Xingni Zhou download

https://ebookbell.com/product/programming-in-c-volume-1-basic-
data-structures-and-program-statements-xingni-zhou-50339330

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.

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


Trainer Edition Volume 1 Microsoft

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

Art Of Computer Programming Volume 4a Combinatorial Algorithms Part 1


1st Edition Donald E Knuth

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

Programming In C Volume 2 Composite Data Structures And Modularization

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

Programming In C Volume 2 Composite Data Structures And Modularization


Zhou

https://ebookbell.com/product/programming-in-c-volume-2-composite-
data-structures-and-modularization-zhou-22736722
Ms Course 10266a Programming In C With Microsoft Visual Studio 2010
Trainer Edition Volume 2 Microsoft

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

Thinking In C Volume 2 Practical Programming Us Ed Bruce Eckel

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

Programming In C Object Oriented Features Laxmisha Rai Editor China


Science Publishing Media Ltd Editor

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

Programming In C For Engineering And Science 1st Edition Nyhoff

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

Programming In C Part One Introduction To C Leonard Robbie

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

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

Elementary Synchronous Programming


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

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

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

Programming in C

Volume 1: Basic Data Structures and Program


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

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

ISBN 978-3-11-069117-7
e-ISBN (PDF) 978-3-11-069232-7
e-ISBN (EPUB) 978-3-11-069249-5

Library of Congress Control Number: 2020940233

Bibliographic information published by the Deutsche Nationalbibliothek


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

© 2020 Walter de Gruyter GmbH, Berlin/Boston


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

www.degruyter.com
Preface
Ideas of the book

This book is written based on years of teaching experience. To clear up students’


confusion in programming learning, it is more focussed on introducing problems,
analyzing problems, and discussing solutions to the problems. In the process of
teaching programming courses (e.g., C programming, data structure) and discus-
sing with students after class, we discovered that the common problems in pro-
gramming learning could be generalized as four challenges: (1) concepts are too
abstract to understand, (2) there are too many rules to remember, (3) there are few
general principles to follow in programming, and (4) it is hard to debug programs.
Leonhard Euler, a well-known mathematician, once said that teaching mathe-
matics would be meaningless if we do not show students the thinking process of
solving problems. This holds for other subjects or courses as well. It is crucial in
our learning to understand the theory and know the way of thinking when solving
problems. While analyzing the difficulties that students face during learning to pro-
gram, we find that the main issue is it is hard to build up the concept of program-
ming in mind. Besides, it is hard to learn debugging techniques. We try to tackle
these issues, in the order of difficulty, using the following four strategies: (1) focus-
ing on thinking, (2) revealing the nature of problems, (3) putting more emphasis on
debugging, and (4) less on syntax. We also devote more words to the introduction
of problems and why some mechanisms are needed.

1 Focusing on thinking

Donald Knuth, recipient of ACM Turing Award and one of the pioneers of modern
computer science, wrote in his masterpiece, The Art of Computer Programming, that
programming is the process of translating solutions to problems into terms that
computers can “understand,” which is hard to grasp when we first try to use com-
puters [1]. Among all high-level programming languages, C is generally acknowl-
edged to be one of the hardest as it is tedious, abstruse, and has a large set of rules.
A computer is an automated tool. When we try to use computers to solve prob-
lems, limitations on what we can do exist due to their capabilities. In such systems,
where rules are different from the ones we are used to, the experience we had may
not be of any help. Many concepts in programming are unfamiliar to students who
have only had exposure to subjects like mathematics, physics, or chemistry. We
find that students struggle to understand when we simply follow a traditional
textbook.
In Presentation Zen, Garr Reynolds wrote that “Stories can be used for good –
for teaching, sharing, illuminating, and, of course, honest persuasion. . . Story is

https://doi.org/10.1515/9783110692327-202
VI Preface

an important way to engage the audience and appeal to people’s need for logic and
structure in addition to emotion” [2]. Many examples in this book start from inter-
esting stories. We extract programming-related topics from the stories, raise a prob-
lem, and guide readers to think. Then we compare how people and computers solve
the problem, analyze the similarities and differences, and eventually introduce the
programming concept behind the problem. To provide our readers with immersive
experiences, we engage Prof. Brown and his family into our discussions. Sometimes
Prof. Brown raises a question from a beginner’s perspective and tries to find a solu-
tion; at other times, he takes part in the discussions as an expert. Mrs. Brown, on
the other hand, knows nothing about programming and sometimes says funny
things regarding programming. Their son, Daniel, is still in elementary school and
often asks naive questions as well. Students, colleagues, and relatives of Prof.
Brown also make cameo appearances in our storytelling. This is also a practice of
lessons from Prof. Takeo Kanade, who talked about his success in research –
“Think like an amateur, do as an expert” [3].

As we work with the same concept from slightly different angles and investigate questions sur-
rounding it, we build even more and deeper connections. Collectively, this web of connections
and associations comprises what we think of informally as understanding . . . “For a memory to
persist, the incoming information must be thoroughly and deeply processed. This is accom-
plished by attending to the information and associating it meaningfully and systematically with
knowledge already well established in memory” . . . Rather than memorizing individual bits of in-
formation, we are dealing with patterns and strands of logic that allow us to come closer to see-
ing something whole. (The One World Schoolhouse: Education Reimagined, Salman Khan) [4]

By analyzing similarities and differences between how humans and computers


solve problems, this book explores methods of doing logical thinking based on
characteristics of computers. With these characteristics in mind, we introduce the
list method for reading programs, methods for designing algorithms, and classic de-
scription methods for algorithms. Using these methods, students can learn reading
programs before writing programs, which enable them to grasp general approaches
to programming at the macro level and to establish a mindset of programming.

2 Revealing the nature

Concentrating on the nature of problems is particularly important for programmers. The


amount of knowledge a programmer needs to know is enormous and is still increasing.
Programmers often find themselves falling behind the trend and focusing on nature is the only
solution. Many new technologies are based on concepts that have been established for dozens
of years. Never will knowledge of low-level architecture become obsolete, nor will that of algo-
rithms, data structures and programming theories. (Dark Time, Weipeng Liu) [5]

There is no formula for programming. Although one may find some patterns from
studying numerous examples, it can be tricky to figure out why certain rules exist
Preface VII

in programming languages. It is crucial to understand both how and why because


one’s understanding of syntax rules can be strengthened through exploring the the-
ories behind them. By this, one becomes more familiar with rules and can eventu-
ally apply them in practice. Focusing on the nature helps students learn to solve
problems with computers more efficiently. This book explains many concepts by in-
troducing problems in practice. We compare correlated concepts from different per-
spectives and extract key elements from important or correlated concepts so that
students can obtain a better understanding.

3 Emphasizing debugging

“No matter how well a program is designed or how self-explanatory its documents
are, it is worthless if it outputs wrong results. (Debugging C++: Troubleshooting for
Programmers, Chris H. Pappas & William H. Murray) [6]” Errors often exist in
human-made devices or equipment, with software being an exception. Software is
delivered in the form of binary code, which does not tolerate errors. However, the
way we think, that is, fuzzy and error-prone, makes it difficult to write completely
correct code in the first attempt.
Yinkui Zhang pointed out in his book Debugging Software that “debugging tech-
niques are the most powerful tools to solve complicated software problems. If solv-
ing these problems were a battle, debugging techniques would be an unstoppable
weapon that strikes critically. It is not hard to learn debugger commands, but it is
tricky to use debuggers to find bugs” [7]. It takes effort to gain experience and mas-
ter debugging skills, especially for beginners. This is also why many students be-
come afraid of programming.
“You can draw an analogy between program debugging and solving a homi-
cide. In virtually all murder mystery novels, the mystery is solved by careful analy-
sis of the clues and by piecing together seemingly insignificant details. (The Art of
Software Testing, Glenford J. Myers) [8]” “Debugging is somewhat like hunting or
fishing: the same emotions, passions, and excitement. Lying long in ambush is in
the long run rewarded by a victory invisible to the world. (Eugene Kotsuba) [9]” By
mastering debugging skills, readers can find and fix bugs independently in their
learning and developing, which in turn increases their interest and helps them gain
confidence.
In addition to finding errors in programs, debugging also helps us understand
many concepts in programming such as address, memory, assignment, passing ar-
guments, and scope. Demonstrating the debugging process gives students a more
intuitive explanation than describing the concepts using abstract words. “Not only
do debuggers help us finding errors in programs, they also walk us through other
software, the operating system, and underlying hardware. (Debugging Software,
Yinkui Zhang) [10]” Debuggers share very similar, if not identical, ways of working,
VIII Preface

“The first debugger in the MS-DOS world was Debug.com . . . New debuggers ap-
pear like mushrooms after a warm rain. However, most of them are not far in ad-
vance of the prototype, differing from it only in the interface. (Hacker Debugging
Uncovered, Kris Kaspersky) [11]” Mastering debugging techniques helps learn other
computer science subjects, so it should be an essential part of programming
courses.
I had been a developer in industry for many years and spent over 4 years as a
member of the development team of a State Science and Technology Prize-winning
software. Furthermore, I engaged in other software engineering activities as well,
including installing and setting up software for users and customer services. This
allowed me to gain practical experience in testing and debugging. When my stu-
dents ask me for help on their codes, I could quickly find errors by debugging and
asking them if the results are as expected, even if I did not know the logic of their
tasks. I have always insisted on demonstrating the debugging process in class. I
would show the debugging process of example programs at students’ request.
However, I later discovered that students still failed to understand, even if I did this
in class. The reason is that debugging is a complex process, and it is tricky to ex-
plain different data structures, code logic, and debugging skills in a few words.
While students may manage to understand in class, there are few written resources
they can refer to when reviewing later. Hence, a large amount of debugging pro-
cesses of important examples and skills we used are “persisted” into this book, so
that students can refer to when learning to debug. Debugging can be extremely dif-
ferent for programs and the number of skills used can be large, so this book will
only cover the basics, yet there are few books of the same kind that cover as many
skills like these. Not many books exist that specialize in debugging either.
Programming is a process that requires continuous changes. A program often
needs to be tested and debugged multiple times. This book also covers how and
when test cases are designed to make readers realize the importance of testing and
grasp the concept of program robustness from the very beginning.

4 Less on syntax

“Putting less emphasis on syntax” does not mean ignoring it. Instead, we start from
core syntax rules and let beginners remember after understanding them. Therefore,
readers can master syntax step by step instead of feeling confused by being exposed
to all the rules of the C language at once. For advanced, sophisticated, or uncom-
mon syntax, it suffices to know how they are categorized and how to look up their
usage in documents.
Introduction
This book explores the methodology of the entire process of solving problems with
computers. Following the workflow of how computers solve problems, the book
walks through how data are stored, processed, and the results are produced. This
book analyzes concepts by introducing problems and drawing analogies. It de-
scribes the entire workflow in a top-down manner: from the description of algo-
rithms, analysis of data and code implementation to testing, as well as debugging
and validation of results. In this way, it is easier for beginners to understand and
master programming thinking and methods. This book makes new concepts easy to
learn by introducing real-life problems and discussing their solutions, leading to a
less stressful and more exciting learning process. With the help of figures and ta-
bles, the contents of this book are straightforward for readers to understand easily.

https://doi.org/10.1515/9783110692327-203
Structure of content
This book studies the methodology of problem-solving with computers. Following
the workflow of computers, we walk through how data are stored, processed, and
how the result is produced. By introducing real-life examples and drawing analo-
gies, we describe the whole process in a top-down manner: from the description of
algorithms, analysis of data and code implementation to testing, as well as debug-
ging and validation of results.
The introduction to data starts from their basic forms. As the complexity of
problems increases, we gradually show how data are organized and stored in com-
puters by discussing different methods of organizing data, such as arrays, memory
addresses, compound data, and files. In addition, we also cover input and output
methods of data.
Algorithms describe procedures and ways of solving problems. Computer algo-
rithms should be designed following the traits of computers. Computer algorithms
are implemented by program statements, which have their own syntaxes or usages.
Programs have basic control flows and their development needs specific procedures
and methods.
As the problems become more sophisticated, it is necessary to use multiple
modules of code instead of one. This book demonstrates how to use functions by
showing mechanisms we need for larger-scale problems.
When coding is completed, we need to test the code and debug if the results
are not as expected. This book introduces the principles of designing test cases,
runtime environment of programs, and techniques of debugging.
There are various exercises in this book, from relatively simple warm-up and
basic exercises to normal and hard homework problems. This helps readers prog-
ress smoothly and stay motivated.
This textbook comprises two volumes. Volume I, Basic Data and Programming
Statements, covers basic programming concepts such as introduction to algorithms,
basic data, and programming statements; whereas Volume II, Composite Data and
Modularity, concentrates on advanced concepts such as arrays, composite types,
pointers, and functions.

https://doi.org/10.1515/9783110692327-204
Division of work
Among all chapters in the two volumes, the ones on preprocessing and files are
written by Lei Feng. Xingni Zhou wrote the rest. Final compilation and editing was
done by Qiguang Miao.

https://doi.org/10.1515/9783110692327-205
Notes
Created in 1972, C is “old” compared to many high-level programming languages.
Starting from the American National Standards Institute C programming (ANSI C),
there have been a series of standards after continuous revision. This book is based
on ANSI C standard and includes syntaxes that have been modified in C99 or C11.
As they do not interfere with the main contents of this book, we decided to follow
our “Less on Syntax” principle and did not modify them according to the latest
standard.
There are two types of examples in this book, namely “Example” and “Program
reading exercise.” An “Example” usually includes analysis of data structure, de-
scription of algorithms, code implementation, and debugging process. A “Program
reading exercise,” on the other hand, only describes the problem and demonstrates
the sample code, along with the analysis for the readers as a practice of the list
method.
To be typesetting-friendly, codes are formatted compactly. For instance, open-
ing brackets do not have their own lines.
All sample programs have been tested under Visual C++ 6.0 environment.
Despite being outdated, it has a smaller installation size and better compatibility.
Moreover, the theory behind debugging is universal and is not limited to a specific
language or runtime.

https://doi.org/10.1515/9783110692327-206
Acknowledgments
After working in the industry as a programmer for years, I came back to college to
become a teacher. During the first few years of teaching, I held many discussions
on methods and ideas in programming teaching with my father, who had been
teaching further mathematics all his life. Sometimes, he found my ideas valuable
and would encourage me to write them out.
After spending more time teaching C language and data structure courses, I grad-
ually realized what was challenging for students to learn programming during my
interaction with them. With this in mind, I tried to change my way of teaching so that
students could gain computational thinking. I was then suggested by my students in
the data structure class to write a book on data structure because they thought my
methods were helpful and could make a unique book. As teaching data structure and
teaching C language share the same ideas, I decided to write on both topics.
I would like to acknowledge my father for inspiring my dream and my students
for making this dream come true. Friendship with my students is heartwarming and
overwhelming. It is their support and help that makes this book possible. It is them
who had encouraged me to complete this book aiming to help beginners enter the
realm of programming. I wish this book can become a torch that lights up the road
of exploring for every learner so that they gain more satisfaction instead of frustra-
tion and enjoy their learning process.
I would like to appreciate Xin Dong from Xi an Academy of Fine Arts for the
beautiful illustrations in this book.
My appreciation also goes to my colleagues Zhiyuan Ren and Dechun Sun for
their help on exercises in this book.
I am grateful to my students Yucheng Qu, Renlong Tu, Meng Sun, Shan Huang,
Bin Yuan, Yu Ding, Liping Guo, Yunchong Song, and Jingzhe Fan for their help in
completing this book. My thanks also go to colleagues and students that shared
their opinions and suggestions. They made me to introspect about drawbacks in my
past teaching and writing. Consequently, I started to think from psychological and
cognitive perspectives and made improvements, such as reinforcing problem intro-
duction and changing my way of storytelling. These improvements can be found in
Data Structures and Algorithms Analysis – New Perspectives.
My thanks also go to Mr. Zhe Jiang for his work on localization of the manuscript.
Rewrite of this book after years (Chinese edition has already been reprinted) is
like a rebirth. I would like to quote my 2019 spring appreciation to conclude this

https://doi.org/10.1515/9783110692327-207
XVIII Acknowledgments

acknowledgment: “Profusion of flowers, blossoming of lives; along with auspicious


clouds, it is spring we celebrate.”

Xingni Zhou
xnzhou@xidian.edu.cn
In Chang’an, midsummer 2020
Contents
Preface V

Introduction IX

Structure of content XI

Division of work XIII

Notes XV

Acknowledgments XVII

1 Introduction to programs 1
1.1 Concept of flows 1
1.1.1 About flows 1
1.1.2 Expression of flows 4
1.1.2.1 Flowchart 5
1.1.2.2 Pseudo code 5
1.1.3 Basic logical structure of flows 6
1.1.3.1 Sequential structure 6
1.1.3.2 Branch structure 6
1.1.3.3 Loop structure 8
1.1.3.4 Logical structure of flows 11
1.1.3.5 Expression of basic flow structures 12
1.2 Concept of programs 13
1.2.1 Automatic flows 14
1.2.2 Concept of programs and programming languages 14
1.2.2.1 Programming languages 15
1.2.2.2 Machine languages 15
1.2.2.3 Assembly languages 16
1.2.2.4 High-level languages 16
1.2.3 Execution characteristics of programs 18
1.2.4 Workflow of computers 18
1.3 Components of programs 20
1.3.1 Problem-solving with computer: data 20
1.3.2 Problem-solving with computer: processing 22
1.3.3 Problem-solving with computers: results 23
1.4 Development process of programs 25
1.4.1 Case study 25
1.4.1.1 Using a calculator 25
XX Contents

1.4.1.2 Using a computer 25


1.4.2 Basic steps of program development 26
1.4.3 Example of problem-solving with computers 27
1.4.4 Flow of program development 34
1.5 Introduction to C programs 35
1.5.1 Sample C programs 36
1.5.2 Structure of C programs 39
1.5.3 Coding style requirements 41
1.6 Summary 42
1.7 Exercises 44
1.7.1 Multiple-choice questions 44

2 Algorithms 47
2.1 Concept of algorithms 47
2.1.1 Algorithms in practice 47
2.1.2 Definition of algorithms 48
2.1.3 Characteristics of algorithms 50
2.2 Representation of algorithms 50
2.2.1 Top-down stepwise refinement method 50
2.2.2 Example of representation of algorithms 52
2.3 Effectiveness of algorithms 55
2.3.1 Example of algorithms 57
2.3.2 Computational thinking 59
2.4 Universality of algorithms 60
2.4.1 Solutions to classic problems 60
2.4.2 Three phases of problem-solving with computers 62
2.4.3 Characteristics of computer algorithms 63
2.5 Comprehensiveness of algorithms 63
2.5.1 Algorithm analysis: Starting from normal cases 64
2.5.1.1 Problem analysis 64
2.5.1.2 Manual method 64
2.5.1.3 Analysis of computer solutions 65
2.5.1.4 Comparison of manual method and computer method 66
2.5.1.5 Algorithm description 66
2.5.1.6 Analysis of execution process 67
2.5.1.7 Testing 68
2.5.1.8 Summary of algorithm design procedures 70
2.5.2 Algorithm analysis: Starting from corner cases 70
2.5.2.1 Problem description 70
2.5.2.2 Ideas of algorithm 71
2.5.3 Keys of algorithm design 72
Contents XXI

2.6 Procedures of algorithm design and characteristics


of algorithms 72
2.6.1 Position of algorithms in the process of solving problems with
computers 72
2.6.2 General process of algorithm design 73
2.6.3 Characteristics of algorithms 74
2.6.4 Characteristics of good algorithms 74
2.7 Summary 76
2.8 Exercises 77
2.8.1 Multiple-choice questions 77
2.8.2 Fill in the tables 79
2.8.3 Algorithm design 80

3 Basic data types 83


3.1 Constants and variables 83
3.1.1 Constants 83
3.1.2 Variables 86
3.1.2.1 Key elements of variables 86
3.1.2.2 Rules of variable naming 88
3.1.2.3 Method of requesting memory space 89
3.1.2.4 Usage of memory space 90
3.2 Data types 93
3.2.1 Representation of information in computers 94
3.2.1.1 Binary system 94
3.2.1.2 Binary representation 94
3.2.2 Processing of information in computers 95
3.2.2.1 Modular system 96
3.2.2.2 Binary modular system 96
3.2.2.3 Representation of numbers in binary modular system 97
3.2.2.4 Range of binary system 98
3.2.3 Basic data types in C 99
3.3 Storage rules of integers 101
3.3.1 Signed integers 102
3.3.2 Unsigned integers 102
3.3.3 Characters 103
3.4 Storage rules of real numbers 104
3.4.1 Representation of real numbers 105
3.4.2 Representation of floating-point numbers 105
3.4.3 Display precision and range of floating-point numbers 108
3.5 Operators and expressions 109
3.5.1 Operators 110
3.5.2 Expressions 110
XXII Contents

3.5.3 Precedence of operators 110


3.5.4 Associativity of operators 112
3.6 Numerical operations 113
3.6.1 Arithmetic operators and expressions 113
3.6.1.1 Arithmetic operators and expressions 113
3.6.1.2 Increment and decrement operation 116
3.6.2 Overflow problems in data operations 118
3.7 Logical operations 119
3.7.1 Relational operations 119
3.7.2 Logical operations 121
3.7.2.1 Example of Relation Problem 121
3.7.2.2 Definition of logical operations 121
3.7.2.3 Examples of Logical Operations 122
3.7.2.4 Rules of logical operations 125
3.8 Type conversion 125
3.8.1 Computation of data of mixed types in real life 125
3.8.2 Type conversion rules in C 127
3.8.3 Forced-type conversion 128
3.8.4 Automatic-type conversion 130
3.9 Other operations 131
3.9.1 Conditional expressions 131
3.9.2 sizeof operator 133
3.9.3 Assignment operator and expressions 133
3.9.4 Compound assignment operators 134
3.9.5 Comma operator and comma expressions 134
3.10 Summary 135
3.11 Exercises 136
3.11.1 Multiple-choice questions 136
3.11.2 Fill in the tables 138
3.11.3 Programming exercises 140

4 Input/output 141
4.1 Concept of input/output 141
4.1.1 Standard input/output 142
4.1.2 Standard library functions of C 142
4.1.3 Header files 143
4.2 Data output 144
4.2.1 Character output functions 144
4.2.2 String output function 145
4.2.3 Formatted output function 146
4.2.3.1 Syntax and signature of formatted output function 146
4.2.3.2 Output format specifiers 148
Contents XXIII

4.2.3.3 Structure of format control sequence 148


4.2.3.4 Subspecifiers 148
4.3 Data input 150
4.3.1 Character input function 151
4.3.2 String input function 153
4.3.3 Formatted Input function 154
4.4 Typical problems of using formatted input function 160
4.4.1 Typical problems of scanf input 160
4.4.1.1 Common mistake of using scanf 1: wrong address argument 161
4.4.1.2 Common mistake of using scanf 2: argument type not compatible
with type specifier 162
4.4.1.3 Common mistake of using scanf 3: argument type compatible
with type specifier 163
4.4.1.4 Common mistake of using scanf 4: '\n' used as newline 165
4.5 Summary 166
4.6 Exercises 167
4.6.1 Multiple-choice questions 167
4.6.2 Fill in the tables 168
4.6.3 Programming exercises 170

5 Program statements 171


5.1 Sequential structure 171
5.2 Double branch structure 174
5.2.1 Syntax of double branch structure 174
5.2.2 Role of compound statements 175
5.2.3 Example of if statements 176
5.2.4 Nested if-else statements 179
5.2.4.1 Nesting rule of if-else 179
5.2.4.2 Note on using nested if-else 180
5.3 Multiple branch structure 182
5.3.1 Introduction of multiple branch problems 182
5.3.2 Syntax of multiple branch structure 185
5.3.2.1 Multiple branch structure model and grammatical
representation 185
5.3.2.2 Grammar test of switch statements 185
5.3.2.3 Refined switch statements model and grammar
representation 186
5.3.2.4 Execution process of switch statements 187
5.3.2.5 Testing the refined program 188
5.3.3 Example of multiple branch structure 188
5.3.4 Comparison of various branch structure statements 194
5.4 Introduction of loop problems 194
XXIV Contents

5.4.1 Analysis of key elements in loops 194


5.4.2 Three key elements of loops 197
5.4.3 Loop statements 198
5.5 While loops 199
5.5.1 Syntax of while loops 199
5.5.2 Validation of necessity of the key elements 199
5.5.3 Example of while loops 205
5.5.4 Methods of loop controlling 210
5.6 Do-while loops 210
5.6.1 Syntax of do-while loops 210
5.6.2 Use case of do-while 214
5.6.3 Example of do-while loops 214
5.7 Alternative form of while loops 216
5.7.1 Syntax of for loops 216
5.7.2 Example of for statements 217
5.8 Infinite loops 219
5.8.1 Infinite loops in practice 219
5.8.2 Infinite loops using while statement 220
5.8.3 Infinite loops using for statement 221
5.9 Interruption of loops 223
5.9.1 Interruption of loops in practice 223
5.9.1.1 Example of interruption of loops 223
5.9.1.2 Early termination mechanism of loops 224
5.9.2 Jumping out of loops with break statement 225
5.9.3 Jumping inside loops with continue statement 229
5.9.3.1 Functionality of continue statement 229
5.9.3.2 Role of continue in different loops 230
5.10 Free jump mechanism 232
5.10.1 Concept of free jump 232
5.10.2 Syntax of unconditional jump statement 233
5.10.3 Example of unconditional jump statement 234
5.10.4 Characteristics of goto statements 235
5.10.4.1 Jumping out of a nested loop directly 235
5.10.4.2 Flexible jumps 236
5.10.4.3 Note on using goto statements 236
5.11 Summary 237
5.12 Exercises 239
5.12.1 Multiple-choice questions 239
5.12.2 Fill in the tables 241
5.12.3 Programming exercises 243
Contents XXV

6 Preprocessing: work before compilation 245


6.1 Introduction 245
6.1.1 Preprocessing 246
6.1.2 Preprocessing directives 246
6.2 Macro definition 247
6.2.1 Simple macro definition 247
6.2.2 Macro definitions with parameters 250
6.2.3 Side effects of macros 252
6.3 File inclusion 252
6.4 Conditional compilation 254
6.4.1 Format of conditional compilation 1 255
6.4.2 Format of conditional compilation 2 256
6.4.3 Format of conditional compilation 3 257
6.4.4 Nested conditional compilation directives 258
6.5 Summary 259
6.6 Exercises 261
6.6.1 Multiple-choice questions 261
6.6.2 Fill in the tables 262
6.6.3 Programming exercises 264

7 Execution of programs 267


7.1 Runtime environment of programs 267
7.1.1 Main screen of integrated environment 269
7.1.2 Create a project 270
7.1.3 Create a source file 273
7.1.4 Edit a source file 273
7.1.5 Compile a source file 275
7.1.6 Link programs 277
7.1.7 Execute program 278
7.2 Testing 279
7.2.1 Introduction 279
7.2.1.1 Defect in arithmetic question generator 279
7.2.1.2 Error handling in the n! program 280
7.2.2 Program testing 281
7.2.2.1 Errors and warnings 281
7.2.2.2 Definition of testing 282
7.2.2.3 Purpose of testing 282
7.2.2.4 Principles of test case design 283
7.2.2.5 Methods of testing 283
7.2.2.6 Basic approaches to test case design 284
7.2.2.7 Order of testing 284
XXVI Contents

7.3 Concept of debugging 286


7.3.1 Bug and debug 286
7.3.2 Bugs are everywhere 287
7.3.3 Difficulties in debugging 287
7.4 Methodology of debugging 289
7.4.1 Introduction 289
7.4.1.1 Finding errors in a domino sequence 289
7.4.1.2 Collapse of the domino sequence 289
7.4.2 Basic flow of debugging 290
7.4.3 Discussion on methods of finding errors in programs 291
7.4.3.1 Analysis of flow of program execution 291
7.4.3.2 Relations between modules 292
7.4.3.3 Problems involved in error finding 292
7.4.4 Exploration of tracing methods 294
7.4.4.1 Trace by statements 294
7.4.4.2 Trace by segments 295
7.4.4.3 Reversed inspection of call stack 296
7.5 Debugging tools 297
7.5.1 Functions of debugger in IDE 297
7.5.2 Debugging commands 299
7.5.2.1 Enter the debugging environment 299
7.5.2.2 Commands controlling program execution 299
7.5.2.3 Set breakpoints 299
7.5.2.4 Inspect execution status 301
7.6 Examples of debugging 304
7.6.1 Demonstration of basic debugging steps 304
7.6.1.1 Tracing by setting breakpoints 304
7.6.1.2 Stepwise tracing 306
7.6.2 Example of debugging 308
7.6.2.1 Editing the code 309
7.6.2.2 Compilation 310
7.6.2.3 Linking 313
7.6.2.4 Execution 316
7.6.2.5 Debugging 316
7.6.3 Example of using the call stack 320
7.6.4 Example of using data breakpoint 324
7.6.4.1 Source code and execution result 324
7.6.4.2 Debugging plan 324
7.6.4.3 Tracing and debugging 325
7.7 Summary 327
Contents XXVII

7.8 Exercises 329


7.8.1 Multiple-choice questions 329
7.8.2 Debugging exercises 329

Appendix A Precedence and associativity of operators 333

Appendix B ASCII table 335

Appendix C Common library functions of C 337

Appendix D Common escape characters 347

Appendix E Bitwise operations 349

Index 353
1 Introduction to programs

Main contents
– Concept of flows
– Concept of programs
– Methods of program design
– A brief introduction to C programs

Learning objectives
– Know the concept of programs
– Understand the basic steps of program design
– Know the basic structure of C programs

1.1 Concept of flows

We use computers to help us work efficiently. How do computers work then? Before
answering this question, let us take a look at how humans solve problems and then
analyze how we think and what methods we use when solving problems.

1.1.1 About flows

Let us look at some flows in real life first.


There are several sessions in the opening ceremony at a college, as shown in
Figure 1.1, where the order of operation is an order of time and is represented by
the arrowed line. Arranging every session in the order of their time of completion,
we obtain a stream of procedures, which we call a flow.
Many of us have traveled by train before and have experience of purchasing
railway tickets. Figure 1.2 shows steps of buying tickets at the ticket office. As
shown in the figure, the flow of buying tickets is a description of the entire process
that starts from setting up a task and completes when achieving the goal by execut-
ing some actions.
Bread is a typical staple food. Baking bread is somewhat a complicated process.
The main steps of its production process are shown in Figure 1.3. We process raw
materials using specific devices in a particular order and eventually obtain finished
goods. This is called the “production flow.”
Many of us may travel by air for longer trips. The boarding flow shown in
Figure 1.4 can clearly guide first-time flyers.
By observing these examples, it is clear that the purpose of flow, be it a work
flow or a production flow, is to achieve a certain goal or to obtain a certain product.

https://doi.org/10.1515/9783110692327-001
2 1 Introduction to programs

Case Study 1

Flow of opening ceremony


Singing the national anthem session

Introducing college administration team


Order of operation

Playing the orientation video

Speech by teacher representative

Speech by current student representative Flow: a stream of


procedures that
Speech by incoming student representative complete in order
as time elapses
Speech by headmaster

Singing the college anthem

Figure 1.1: Flow of opening ceremony.

Case Study 2
Flow of purchasing tickets through ticket office
Step 1: The passenger provides information on trip date, destination, etc.
Step 2: The staff finds trains available on that day
Step 3: The passenger chooses a train and determines number of tickets to buy
Step 4: The passenger pays the fare and collects tickets

Figure 1.2: Flow of purchasing tickets at the ticket office.

Case Study 3
Flow of baking bread

Collect ingredients Recover the dough

Knead the dough Bake

Ferment Cool down

Mold the dough Finish

Figure 1.3: Flow of baking bread.


Case Study 4

Boarding flow

Domestic
flight
Safety
check Boarding Scan
Boarding Boarding
Check-in pass boarding
gate broadcast
Customs check pass
International check
flight
Inspection Shuttle
quarantine bus
Airfield Aircraft stand

Immigration
inspection
On-
Safety check board

Figure 1.4: Boarding flow in airports.


1.1 Concept of flows
3
4 1 Introduction to programs

It describes the entire process of completing a task, a job, or manufacturing a prod-


uct. Every flow, regardless of what it describes, consists of a series of sessions and
orders of operations as shown in Figure 1.5.

Flow
A flow describes the entire process of completing a task, a job or manufacturing a product.
A flow consists of a series of sessions and orders of operations.

Session: Phases or procedures during completion of a task, a job or manufacture of a


product.

Order of operation: Time order of sessions in a flow.

Figure 1.5: Concept of flows.

1.1.2 Expression of flows

Flows can be expressed in many ways, as seen in previous examples. The flow of
an opening ceremony is shown in a flowchart. The flow of purchasing tickets is de-
scribed in plain words. The boarding flow is shown in a figure. In addition, flows
can be expressed as a table, model, video, etc. In programming, flowcharts and
pseudo codes are often used to describe a flow as shown in Figure 1.6.

Flowcharts and
Expressions of flows
pseudo code are
• Flowchart • Figure often used to
• Text • Model describe flows in
• Table • Animation programming

Flowchart
A flowchart is one way to express steps in a process in figures. It consists of some
shapes and flowlines , where shapes indicate type of operations, text and signs in
each shape describe content of an operation and flowlines indicate order of
operations.

Pseudo code
Pseudo code uses words and symbols that fall in between natural languages and
computer languages to describe processing process of problems.

Figure 1.6: Common ways of expression of flows in programming.

A flowchart depicts a process as a figure, whereas the pseudo code uses words and
symbols to describe a process. Pseudo code does not use graphical symbols, which
1.1 Concept of flows 5

makes it easier to write and understand, more compact, and more convenient to
transform into programs.
This book uses pseudo code to describe program flows in most cases. Procedures
human use to solve a problem is also known as “algorithms.”

1.1.2.1 Flowchart
American National Standards Institute (ANSI) standardized some common flow-
chart symbols that have been adopted by programmers from all over the world. The
most frequently used symbols can be found in Figure 1.7. Process symbol, decision
symbol, and input/output symbol are used to represent sessions in different situa-
tions. The flowline symbol is an arrowed line, which is used to show the order of
operation. Using graphical symbols to represent a flow is more intuitive and easier
to comprehend.

Symbol Name Meaning


Terminal Indicates beginning and ending of a flow

Process Represents normal operations


Determines whether a given condition is met and yields true or false.
Decision Session
Result needs to be labeled at exits
Input/Output Input and output of data
Connects process or decision symbol, shows path and direction of Order of
Flowline operation
flows
Connector Connects flowlines drawn in different places

Figure 1.7: Common flowchart symbols.

1.1.2.2 Pseudo code


Pseudo code shows the execution process and algorithm of programs in the format of
code. It does not rely on a certain programming language. It uses the structure and
format of programming language to describe the execution process of a program.
Hence, it cannot be compiled by compilers. Using pseudo code allows to show the
execution process of programs in a way that is easier to understand and express.

Knowledge ABC Flowchart and pseudo code


From the late 1940s to the mid 1970s, flowchart has been the primary tool in process design.
The main advantages of flowcharts are: it uses standard and straightforward symbols, is easy
to draw, has a clear and logical structure, and is easier to describe and understand. Its intuitive
depiction of control flows allows beginners to handle them painlessly. Moreover, flowchart is
time honored and familiar to humans. Consequently, it is still widely used today although many
people advocate obsoleting it due to its disadvantages. A flowchart is a description of methods,
ideas, or algorithms people use to solve problems. However, avoiding flowcharts has been the lat-
est trend. One of its major disadvantages is that it takes up more space. Besides, the use of flow-
lines has few restrictions, thus one can make a flow growing in an arbitrary direction. This results in
6 1 Introduction to programs

challenges when reading or modifying a program. Secondly, flowchart is not helpful in the design
of structured programs. It is not a tool that allows continuous improvement because it forces pro-
grammers to consider the control flow rather than the overall structure of programs in an early
stage.
When implementing the same algorithm using different programming languages, people re-
alize that these implementations (note that it is not functionality) are often different as well. It
can be hard for a programmer who is proficient in one language to understand the functionality
of a program written in another language, as the form of programming languages puts limita-
tions on his/her understanding of the critical parts. Therefore, pseudo code was created.
We often use pseudo code when considering the functionality (instead of the implementa-
tion) of an algorithm. It is also used in computer science education so that all programmers can
understand.
Pseudo code is written in the form of programming languages to indicate the functionality of
an algorithm. It is similar to natural languages instead of programming languages (such as
Java, C++, Delphi, etc). Using pseudo code, the execution process of an algorithm can be de-
scribed in a way that is close to natural language. We may use any language in pseudo code, be
it Chinese or English, but the key is to show what the program intends to do. Pseudo code helps
us express algorithms without considering implementation.

1.1.3 Basic logical structure of flows

What logical features does the description of a flow that solves a problem have? We
shall discuss the answer soon.
Let us consider a real-life flow first: setting up a washing machine.

1.1.3.1 Sequential structure


Mr. Brown is a computer science professor in a college who seldom does housework
because he is usually busy working. However, his wife, Mrs. Brown, will be traveling
for a few days, so he has to learn how to use the washing machine. She only told him
the basic setup, as shown in Figure 1.8, as she was afraid that Mr. Brown could not
remember all the functionalities the washing machine has if she did not do so.
The operations of the washing machine are executed in an order that is deter-
mined by logical relations between each operation. For example, soaking should
happen before washing. Mr. Brown took notes carefully and made a flowchart of
washing operations based on the execution order as illustrated in Figure 1.9. In this
washing program, the preset operations are arranged sequentially. Thus, the struc-
ture of these operations is called a “sequential structure.”

1.1.3.2 Branch structure


In his first attempt, he put many clothes into the washing machine and then config-
ured it as how he was taught. However, he found that the washing machine was
1.1 Concept of flows 7

Washing Sequential
case 1 structure

Basic washing program


Medium load
Settings: Each step is
• Medium water level executed in an
order that is
• Soak for 20 minutes determined by
• Wash for 20 minutes logical relations
between them
• Rinse once for 5
minutes
• Spin-dry for 3 minutes

Figure 1.8: Washing case 1.

Start

Medium water level

Soak

Wash

Rinse

Spin-dry

End

Figure 1.9: Flow of washing process with sequential structure.

not working smoothly, so he immediately called his wife for help. He was then told
that this washing program was designed for a medium load of clothes and was not
suitable for a large load.
The water level needs to be adjusted according to the clothes load. In this case,
we need to setup water level after determining the amount of clothes as shown
in Figure 1.10. We should choose a high water level for a large load. Otherwise, we
use a medium level, after which we continue with our basic washing program.
Mr. Brown drew a new flowchart (Figure 1.11), which was more intuitive. He
used different configurations for different clothes loads. Such flow where a decision
needs to be made is called “branch structure.” Note that the decision condition is
put in a diamond symbol to make it more noticeable. The diamond symbol means a
decision in the flowchart drawing standard.
8 1 Introduction to programs

Washing Branch
case 2 structure

Configure according to clothes load:


If large load choose high water level
Otherwise choose medium water level
Continue the basic washing program

Figure 1.10: Washing case 2.

Start

Huge load May run into


Y N situation where
we need to make
a decision
High water level Medium water level

Basic washing program

End

Figure 1.11: Flow of washing process with a branch structure.

Thinking about the problem caused by clothes load, Mr. Brown realized that
there should be another water level option for a small load. He later found that it
did exist after investigating the washing machine.
The complete flow of setting up water level is shown in Figure 1.12. If the
clothes load is small, we choose the low water level; if medium, we choose the me-
dium level; and if large, we choose the high level.
Mr. Brown then drew the multiple branch structure flowchart based on his
wife’s description as illustrated in Figure 1.13. This is a branch structure with three
branches. Note that the clothes load is represented as a rectangle instead of a dia-
mond as the diamond symbol is only used when there are two branches in a deci-
sion. More details are covered in the discussion of the selection structure.

1.1.3.3 Loop structure


Mr. Brown started to feel curious and started to investigate the washing machine as if
he was experimenting. He noticed that the washing machine could not rinse properly
with a huge load of clothes. This time he decided to solve the problem without calling
1.1 Concept of flows 9

Washing Branch
case 2 structure
Consider all clothes load situations
Settings:
• If small load
Choose low water level
• If medium load
Choose medium water level
• If large load
Choose high water level
Continue the basic washing program

Figure 1.12: Washing case 2 with multiple branches.

Start
Consider all
clothes load
Clothes load
situations

Small Medium Large

Low water Medium High water


level water level level

Basic washing
program

End

Figure 1.13: Flow of washing process with multiple branch structures.

Mrs. Brown for help. It seemed that he should increase the number of rinses in the
washing program. He then checked the machine and pressed the “Rinse” button one
more time. It turned out that the clothes were rinsed again. The case of multiple
rinses is shown in Figure 1.14, where Mr. Brown increased the number of rinses to
three without changing the rest of the washing program.
However, the way three rinses are expressed in the flow shown in Figure 1.15
seems cumbersome. It will be worse if we have even more rinses. Can we make any
improvements?
10 1 Introduction to programs

Washing
case 3

If we want to rinse thoroughly


Settings:
• Water level settings
• Soak
• Wash
• Rinse 3 times
• Spin-dry
Figure 1.14: Washing case 3.

Water level settings Refinement of


incomplete rinsing
Soak when clothes load
is large
Wash

Rinse

Rinse Can we use a


better way to
Rinse
express 3
Spin-dry rinses?

End

Figure 1.15: Flow of washing program with three rinses.

The refined flow is shown in Figure 1.16. The machine continues rinsing if it has
not rinsed a preset number of times. Otherwise, it proceeds to execute other steps.
A flow with steps that may be repeatedly executed is said to have a loop structure.

Washing Loop Soak


case 3 structure
Wash Has
If we want to rinse repeated
thoroughly operations
Settings: Rinse 3 Y
• Water level settings times?
• Soak
N
• Wash
• Rinse 3 times Rinse
• Spin-dry
Spin-dry

End

Figure 1.16: Flow of washing process with the loop structure.


1.1 Concept of flows 11

1.1.3.4 Logical structure of flows


Based on these examples, the basic logical structure of flows is summarized in
Figure 1.17. A flow structure is the logical structure of the execution of each step.
If there is no decision to be made, it is a sequential structure; if there is a decision
but no repetition, it is a branch structure; otherwise, it is a loop structure with
both decision and repetition.

Start

Problem analysis

T Has F
decision

T F
Has repetition

Loop Branch Sequential


structure structure structure

End

Figure 1.17: Basic logical structure of flows.

Sequential structure, branch structure, and loop structure are the three funda-
mental structures of programs. It has been proven in practice that any flow, no
matter how complex it is, can be constructed by these three basic structures as
shown in Figure 1.18. It is similar to how the three primary colors can be combined
to produce a gamut of colors. They can also be nested to generate programs that
are called “structured programs.”

Sequential, branch and


Sequen- loop structures are the
tial three fundamental
structures of programs

Branch Loop

Figure 1.18: Fundamental structures of programs.


12 1 Introduction to programs

1.1.3.5 Expression of basic flow structures


Now we can summarize expressions of basic flow structures.
The sequential structure consists of several steps that are executed in order. It is
the simplest and most fundamental structure that every algorithm has. To express a
sequential structure, simply list the operations in time order. The rectangle symbol in
flowcharts means “Process” and it represents operations as shown in Figure 1.19.

Flowchart Pseudo code

Operation 1 Operation 1

Operation 2 Operation 2

...
Rectangle
process Operation n Operation n
symbol

Figure 1.19: Expression of sequential structure.

The branch structure tests a preset condition and controls the flow based on the
result as shown in Figure 1.20. In flowcharts, we put the condition into a diamond
symbol. The flow enters different branches based on whether the condition is evalu-
ated to be true or not. If true, the condition is met, the operation set A is executed
(herein the operation set means a set or series of operations); otherwise, the condi-
tion is not met and operation set B is executed. We need to pay attention to the in-
dentation of curly brackets when using pseudo code representation.

Diamond Flowchart Pseudo code


decision
symbol
if (condition)
T F {
Condition Operation set A
}
Note
Operation set Operation set else
indentation
A B {
inside {}
Operation set B
}

Figure 1.20: Expression of branch structure.

The loop structure contains steps that are executed repeatedly under certain condi-
tions. There are two kinds of loop structures: while loops and do-while loops.
1.2 Concept of programs 13

“While loops” test the loop condition first. If it is met, the operation set A is
executed. Otherwise, the loop is terminated. In other words, it tests and executes as
shown in Figure 1.21.

Flowchart Pseudo code

Operation set A while (conditon)


{
Operation set A
Condition }

Test and
execute

Figure 1.21: Expression of while loop structure.

Do-while loops execute operation set A first and test loop condition when the oper-
ations are completed. If the condition is met, the operation set A is executed again.
The loop would n be terminated until the condition is no longer satisfied. In other
words, it executes and tests as shown in Figure 1.22.

Flowchart Pseudo code

Execute
Operation set A and test
do
T {
Condition Operation set A
} while (condition)

Figure 1.22: Expression of do-while loop structure.

1.2 Concept of programs

In the previous section, we discussed methods, procedures humans use to solve


practical problems, and how they are represented. Herein we examine how com-
puters solve problems.
14 1 Introduction to programs

1.2.1 Automatic flows

We have discussed how to configure the washing process in the introduction of the
concept of flows. Herein we are going to focus on how the washing machine runs.
To use a washing machine, we setup the washing program and start it. The machine
automatically completes the necessary operations as shown in Figure 1.23. A pro-
gram is a flow that machines can execute automatically after we setup the steps. In
fact, it is the computer program installed inside that enables washing machines to
run automatically.

Order of operation

Configure
Session
Add detergent Add water Add water

Wash Rinse We set up sessions in


advance and start the
machine, then it can
Drain Drain complete the operations
automatically
Dry Dry

Figure 1.23: Automatic flow of washing machine.

Nowadays, it is quite convenient to buy tickets online. It is made possible by con-


verting the process of purchasing through the ticket office into an automatic flow
that computers can handle (Figure 1.24).

Main steps of purchasing train tickets online


Step 1: Open the website
Step 2: “Search”, input trip date, destination, etc.
Step 3: “Book”, choose a train to book ticket Computers
Step 4: Log into system can simulate
Step 5: Submit an order some manual
Step 6: Pay ticket fare online processes
Step 8: Choose ticket collection method

Figure 1.24: Flow of purchasing tickets online.

1.2.2 Concept of programs and programming languages

Based on the automatic flows mentioned, programs and programming languages


can be formally defined as shown in Figure 1.25.
1.2 Concept of programs 15

Program

A program converts the process of solving a practical problem into a sequence of


instructions using programming languages. To be more specific, it is a flow designed
to be executed by computers automatically, using data that can be accepted by
computers and intending to produce expected result.

Programming language

A programming language is a computer-recognizable language used in communication


between human and computers. Programming languages have fixed symbols and
grammar rules.

Figure 1.25: Programs and programming languages.

1.2.2.1 Programming languages


Programming languages are languages used to write the computer programs. There
are many kinds of programming languages, but generally, they can be categorized
into machine languages, assembly languages, and high-level languages. Assembly
and high-level languages are being widely used nowadays.

1.2.2.2 Machine languages


Computers are built from numerous electronic components. Videos we watch and
music we listen to are merely variation and combination of high and low voltages.
Hence commands that computers receive are simply variation of voltages, namely
high and low voltages. Engineers and computer scientists use “0” and “1” to repre-
sent on and off. These 0’s and 1’s are called “binary codes.” Computers can only
recognize these codes.
Do we write programs using 0’s and 1’s then? The answer is yes. In the early
days of programming, people wrote programs by punching on one-inch wide cards.
There were eight holes on each line and each hole represented one binary bit.
A punched hole represented 1 and an unpunched hole represented 0. Combinations
of holes on each line represented commands. Code written using 0’s and 1’s in this
way is written in machine language. Machine language can transfer commands to
computers directly. Code written in machine languages is flexible and can be exe-
cuted directly and quickly. However, it takes effort for developers to write programs
and it is incredibly inefficient. Moreover, it is hard to comprehend a program in ma-
chine language. Reading and debugging are painful as well. Hence, machine lan-
guages are called “low-level languages.” Machine languages are not universal
either as they are machine-dependent. Specific machine languages can only be
used in certain kinds of machines.
16 1 Introduction to programs

1.2.2.3 Assembly languages


It was not long before programmers found machine languages cumbersome, thus
they started to look for other means to communicate with computers. Is there a way
to write programs using symbols other than “0” and “1” and then translate them
into machine languages? It turned out to be a great idea as assembly languages
were created. In assembly languages, we use mnemonic symbols to replace ma-
chine commands. For example, ADD is used for adding numbers and SUB is used
for subtraction. These symbols make assembly languages more readable. After writ-
ing a program, we need a translation program that converts the program into ma-
chine commands. Such a program is called an assembler. The process of writing a
program in assembly language is shown in Figure 1.26.

Assembly instructions Machine code

Programmer Assembler Computer

Figure 1.26: The process of writing program in assembly language.

The emergence of assembly languages allowed computers to be used in more areas.


However, different computers often have different assembly languages, thus they were
machine-dependent as well. Due to the weak universality, they were also categorized
as low-level language. Nevertheless, they are still being used by people nowadays be-
cause they can be executed more quickly, save memory space, and manipulate hard-
ware more efficiently. They can often be found in these areas: system (including
embedded system) programming, such as operating systems, compilers, drivers, wire-
less communication, DSP, PDA, GPS, etc.; software development where resource, per-
formance, speed, and efficiency are critical issues; as well as reverse engineering that
aims at information security, software maintenance, and cracking software. Even if we
are not going to work on system development or to become a hacker or a cracker,
knowing assembly language is helpful for learning computer architecture, debugging
software, and improving algorithms used in the critical part of programs.

1.2.2.4 High-level languages


To accelerate the developing process, humans created Fortran, the first high-level pro-
gramming language, in 1954. This marked the beginning of a new era of programming.
High-level languages are similar to natural languages and mathematical ex-
pressions. Compared to assembly languages, they combine multiple correlated ma-
chine instructions into single instruction and eliminate hardware manipulation
details that are unrelated to the functionalities of a program. Thus, instructions in a
1.2 Concept of programs 17

program are largely simplified and programmers no longer need a large amount of
hardware knowledge.
The name “high-level language” means these languages are more advanced
than assembly languages. It does not refer to a specific language. Instead, it refers
to many programming languages, such as VB, C, C++, and Delphi, which vary in
syntax and instruction format.
Programs written in high-level languages cannot be recognized by computer di-
rectly. They must be converted for computers to execute. Depending on the way of
conversion, high-level languages can be categorized into two types:
– Interpreted languages: The conversion is similar to simultaneous interpretation
in real life. The interpreter of a language executes a program directly while
translating source code into target code (in machine language) at the same
time. This process is inefficient and applications cannot work without the inter-
preter as there are no executable files generated. However, using an interpreter
is more flexible as we can modify our applications dynamically.
– Compiled languages: Compilation is the process of applications being trans-
lated into object code (with .obj extensions) before being executed. Generated
object programs can be executed without the language runtime, thus it is more
convenient to use and more efficient. However, if any changes are needed, we
have to modify the source code and recompile it into object code to execute.
This can be inconvenient if we do not possess the source code. Many program-
ming languages are compiled languages such as C, C++, and Delphi.

One of the advantages of high-level languages is better portability, which means


programs can run on different types of computers. Compared to assembly lan-
guages, high-level languages are more comfortable to learn and master. Programs
written in these languages are also easier to maintain. However, programmers can-
not manipulate hardware and control operations of computers directly as high-level
languages do not target specific computer systems. Besides, object programs are
larger and run slowly compared to those generated from code written in assembly.

Knowledge ABC ANSI C and C standards


During the 1970s and 1980s, C was widely used on all types of computers, from mainframe com-
puters to microcomputers. This led to different versions of the language. In 1989, the ANSI estab-
lished an entire standard specification for C so that different companies could use the same set
of syntax. This was the C89 standard (also known as ANSI C), which was the earliest standard of C.
In 1990, the International Organization for Standardization (ISO) and the International Electronical
Commission (IEC) adopted the C89 standard as the international standard of C language (known
as C90 standard). After subsequent revisions, the C99 standard (published in 1999) became the
second official standard of C. The C11 standard (published in 2011) is the third official standard
and the latest one.
18 1 Introduction to programs

1.2.3 Execution characteristics of programs

Programs are flows of operations executed by machines. What are their characteristics?
A program is a process of setting up operations and executing them sequen-
tially, which is similar to a domino show as illustrated in Figure 1.27. Many of us
are familiar with domino shows. Their rules are simple: dominoes are aligned in
sequence, each at a certain distance from the next. Builders can create patterns and
images based on meticulous design. Once the first domino has been toppled, a
chain reaction happens and the rest are toppled in order.

Meticulous design
in advance, chain
reaction once
started

Figure 1.27: Characteristics of automatically executed flows.

Another one of such systems that feature meticulous design and chain effect is the
Rube Goldberg machine. It is an extremely well-designed and complicated system
that completes a task in an indirect and overly complicated way. Designers of a Rube
Goldberg machine have to make sure everything is correctly calculated so that each
device in the system can achieve a stated goal at the perfect time. The Rube Goldberg
machine also creates visual effects similar to those of a domino show.

1.2.4 Workflow of computers

Programs are executed automatically in computers. Hence, we need to know how


computers work.
1.2 Concept of programs 19

In the mid-1930s, John von Neumann, a Hungarian-American mathematician,


proposed to use the binary numeral system in digital computers and to write com-
puting programs in advance so that computers could follow the computation se-
quence to complete numerical calculations. Electronic computer systems designed
based on his concepts and theories are now called “von Neumann architecture”
computers. A computer should have data input, data processing, and result output
functionalities. To achieve this, computers must have five basic components as
shown in Figure 1.28.

Computer

Internal
memory (RAM)

Processing

Information External Result


input memory output
(Hard disks)
Programs, data Data

Information
processing

Figure 1.28: Basic components of computers.

They are:
– Input devices for data and programs: keyboards are the most common input
devices.
– Output devices for results of processing: monitors are the most common output
devices.
– Memory units for storing programs and data: there is nonvolatile memory
(hard disks) that can retrieve stored information even after having been power-
cycled and volatile memory such as random-access memory (RAM) that re-
quires power to maintain the stored information.
– Central processing unit (CPU) processes data and controls the execution of
programs.

CPU is the most critical component of computers. It consists of a processor and con-
trol units. The processor is used to complete arithmetic and logical operations. The
decision-making process we have seen in flowcharts is categorized as a logic opera-
tion in computers. The control unit performs instructions fetched from memory
units and provides control signals to other components.
20 1 Introduction to programs

The workflow of a von Neumann architecture computer is shown in Figure 1.29.


The main steps are:
– Input programs and data: Programmers need to store programs to be executed
and related data into random access memory (RAM).
– Fetch instruction: The control unit fetches the first instruction from RAM.
– Fetch data: Based on the instruction in step 2, data are retrieved from memory
units and sent to processors.
– Process: Specified arithmetic and logical operations are carried out in processors.
– Store intermediate results: Intermediate results are sent to a specific address in
RAM. This is done continuously until all instructions are completed.
– Output final result to output devices.

1 6
Program Input Output
RAM Result output
device device
Data

5 3 2

CPU
Processor Control unit
4 Data stream
Control signal

Figure 1.29: Workflow of computers.

1.3 Components of programs

In the workflow of computers, data are sent to memory units through input devices.
The processors perform logical and arithmetic operations under the control of con-
trol units. The final result is presented to users through output devices. The flow
that computers use to solve problems can be divided into three parts: data input,
data processing, and result output as shown in Figure 1.30.

Data Processing Result

Figure 1.30: Flow of problem-solving with computer.

1.3.1 Problem-solving with computer: data

Data in programs are units of information that can be stored in and processed by
computers. If we were computers, as tools for information processing, what issues we
1.3 Components of programs 21

need to handle between us and the data to be processed? Considering the workflow
we saw earlier, the main issues include how information is input, how data are stored
and processed, and how results are output as shown in Figure 1.31.




Internal
memory (RAM)

Information Processor + Result output


input Control unit

External
memory
(Hard disks)

Data
Data in programs are information computers can store and process

Figure 1.31: Relation between computers and data processing.

With hardware architecture and theories of computers in mind, we study the follow-
ing data-related issues: how data are input/output; how data are stored in internal
(and external) memory units, which address they are stored at and how much space
they take up; and how related data are combined and stored according to their char-
acteristics and types, which is a combinatorial data problem in programming.
Issues of data processing include how they are represented in programs and
their computation rules.
In summary, issues related to data in programs can be categorized into mem-
ory-related and input/output devices related as shown in Figure 1.32.

Basic data

Compound data
RAM
Data Processing Result

Data location
We treat external
Input/Output memory as
Input/Output
devices input/output device in
programming

Figure 1.32: Problem-solving with computers: Data.


22 1 Introduction to programs

Memory-related issues include:


– Basic data issues that include how data are stored and calculated.
– Combinatorial data issues that include how data of same and different types
are combined and processed.
– Address issues that determine which location in RAM data should be stored in.

Input/output devices-related issues include how data are input and output. Note
that external memory is deemed input/output device in programming.

1.3.2 Problem-solving with computer: processing

Data processing consists of the description and implementation of the processing


process as shown in Figure 1.33.

Description of
processing Algorithm
process • Description of processing process – algorithms
• Involves form of expression, method of description
and design principles

Data Processing Result

• Program statements: instruction we issue to


Program statements machines
• Flow structure: logical structure of program execution
• Modularization: when the scale of a program is large
Implementation of Flow structure
enough, we need to divide it into correlated parts
processing based on their functionalities. A module is called a
process Modularization “function” in C
• Structure of C programs: consists of main function
Structure of C programs and child functions

Figure 1.33: Problem-solving with computers: processing.

The description of the processing process is nothing but an algorithm. We need to


consider the form of expression, method of description, and design principles when
talking about algorithms.
The implementation of the processing process comprises four topics. The actual
implementation is done by code. Flow structure is the logical structure of program
execution. Basic logical structures of flows include sequential structure, branch
structure, and loop structure. When the scale of a program is large enough, we
need to divide it into correlated parts based on their functionalities. This division is
called modularization. In our daily life, a complex task can be divided into multiple
easy tasks for different people to complete. Each task can be regarded as a module.
Modules are called “functions” in C programs. The structure of C programs consists
of the main function and child functions.
Random documents with unrelated
content Scribd suggests to you:
How to take three button moulds off two strings.

Take two little whipcords of two feet long a-piece, double them
equally so as there may appear four ends; then take three button
moulds, the hole of one of them must be bigger than the rest, and
put one button mould upon the eye or bout of the one cord and
another on the other cord, then take the button mould with the
greatest hole, and let both the bouts be hidden therein; which may
be the better done if you put the eye or bout of the one into the eye
or bout of the other; then pull the middle button upon the same,
being doubled over his fellow, so will the heads seem to be put over
the two cords, you may loose them as you list, and make it seem
manifest to the beholders, which may not see how they are done,
but that the buttons are put upon the two cords without any fraud;
then must you seem to add a more effectual binding of those
buttons to the strings, and make one half of a knot with one of the
ends of each side, which is for no other purpose, but that when the
buttons be taken away, the cords may be seen in the case, which
the beholders supposes them to be in before; for then you have
made your half knots, which in any wise you may not double to
make a perfect knot, you must deliver into the hands of some
stander-by these two cords, namely, two cords evenly set to one
hand, and two in the other, and then with a wager begin to pull off
the buttons, which if you handle nimbley, and in the end cause him
to pull his two ends, the two cords will shew to be placed plainly,
and the buttons to have come thro’ the cords; but those things are
so hard, and long to be described, that I will leave them, whereas I
could shew greater variety.
READER,
I have promised you to write something of con­fed­er­acy, that when
you see or hear some fancy done, you shall be no stranger to it, but
know how to do it as well as any juggler in England, for by con­fed­er­‐
acy mighty wonders are wrought, which seem incredible and
impossible. Some will ask for what reason I do write these things
and set them forth in such a manner, for they say, we know them
already; my answer is, if you do, every one does not; therefore
slight not simple things, for you that seem to be so cunning and so
wary may be imposed on and deceived: what would an ingenious
person give, or how far would he go to learn secrets? I myself would
have gone twenty miles to have learnt the worst fancy in this book; I
would have you take it in good part, and so I proceed to the chapter.
To cure the tooth-ach.
This must be done by con­fed­er­acy, I won many a pint of wine by
it; you must pretend you are grievously troubled with the tooth-ach,
making wry faces and pretending a great deal of pain; then says
your con­fed­er­ate, I will undertake to cure you in a quarter of an
hour, it is a plain but a very safe and easy way, he then takes a
thimble full of salt, puts it into a piece of paper, then says he, Hold
this to your cheek on that side the pain lies, and it will be gone. You
shaking your head at him, asking him, if he can find none to make
sport with but you that are not disposed; he then proffers you to try
his receipt, which, with seeming unwillingness take and hold it to
your cheek a small time, then he will ask you if you find ease, you
spitting much, say, Yes, truly I find it much abated; then he will say,
to perfect it, lay down your paper upon the table, step into the yard
and wash your mouth with a spoonful of cold water: Now (says he
to the company, in your absence) You may see what conceit does, I
will take out the salt, and put in the like quantity of ashes in the
paper; laying it twisted as before in its place, then he coming in,
takes up the paper again, and puts it into his mouth as before, the
company will be laughing and fleering as tho’ you are ignorant, then
privately convey the ashes away with the paper and another paper
of salt like the former, as you must have in readiness as before, hold
to your cheek, your con­fed­er­ate asking you, Well, what think you
now? Why, indeed one would not have thought to have had so soon
an alteration in a little; then will one or another say in company,
Why, do you think you have salt in your mouth? Yes, I saw it taken
out of the box; he will lay you a wager presently, that it is not salt,
when by opening the paper, his folly is discovered, with no small
sport to the company.

To know if it be a head, or woman, and the party to


stand in another room.
This likewise is done by con­fed­er­acy, he that lays it down, says,
What is it? and that is a sign it is a head; for he says, What is it now,
and that is a sign it is a woman: cross and pile in silver is done the
same way. By con­fed­er­acy divers strange things are done; as to
make a man, by muttering some words, to pull off his cloaths, and
so dance naked; thus you may throw a piece of money into a pond,
and bid a boy go to such a secret place where you have hid it, and
he will bring it, and make them believe it is the same that you threw
into the pond, and no other.
So let a con­fed­er­ate take a shilling and put it under a can­dle­stick
on a table at a good distance from you, then you must say,
Gentlemen, you see this shilling, then take your hand and knock it
under the table, and convey it into your pocket: then say, The
shilling is gone, but look under such a can­dle­stick and you will find
it.

Fortunatus’ wishing post, or how to make any person


dance naked.
This feat is more for pastime than any thing else.
You must go and get you a post of about five or six inches long,
and you must then get it turned hollow throughout, so that you may
have a screw made just fit, and then put a needle at each end of the
screw, and have two holes so contrived in the post that you may
fasten two strings in the screw, so as when you pull one end of the
string, the needle will run into your finger, and when you pull hold of
the other end of the string, the needle will run into your thumb,
which will cause great laughter to the campany. If these words are
not sufficient for you to make one by, you may have them at my
house ready made.

To seem to cut a hole in a cloak, scarf, or hand­ker­chief,


and with words to make it whole again.
To do this you must have a piece of the same ready in your
hand, the sample of that you intend to cut; then amongst other
tricks by you, clap your hand upon the place you intend to cut, then
drawing hollow by the false piece, cause it to be cut off, and gripping
your hand, shew the hole from whence the piece came away, which
is in your hand, which is done by pretending to feel in your pocket
for a needle and thread to sew it up again: but drawing your hand
out from your pocket, saying, I have no needle, but I have a charm
will do as well; so muttering some words, bid them blow upon it,
and pulling your hand from the place, does not a little satisfy the
curiosity of the persons which thought they had been damnified.
The Egg Box is looked upon to be as good a trick and
as cunning a slight, as any that is done, but because it
cannot be expressed in words, I have put these figures
underneath to explain it.

A, signifies the egg box, made in the fashion of two bee-hives


put one upon another; B, the upper shell; C, the inner shell, covered
over artificially with the skin of an egg; P the lower part of the shell-
box; putting B, which is the outward shell, upon C, and both upon P,
as it stands, makes the box perfect. To do this trick, call for an egg,
then bid all standers-by look on it, and see that it is a real egg,
setting the box on the table, upon the foot C, take off the upper
part, B, C, with your fore-finger and thumb, then placing the egg in
the box, say, You see it fairly in, and uncovering it again, likewise
say, You shall see me fairly take it out, putting it into your pocket in
their sight; open your box again and say, There is nothing, close
your hand about the middle of your box, and taking B, by the
bottom, say, There is the egg again, which appears to the spectators
to be; so clapping that in again, and take the lid of C, in your finger
and thumb, say, There it is gone again.
This feat is not for a bungler to shew.

To make a room seem to be all on fire, mighty dreadful


to behold.
Take sal armoniack half an ounce, camphire one ounce, aqua
vitæ two ounces, put them into an earthen pot, in the fashion of a
chamber-pot, but something narrow upon the top, then set fire to it,
and the room will seem to them that are in to be all on fire; nay,
themselves will slap their hair and clothes thinking they are all on
fire, when there is no body hurt, unless it be with fright. Have a care
of shewing it to women with child in the room, for yourself would be
frighted if you did not know the trick.
How to eat fire, and to blow it up in your mouth with a
pair of bellows.

Anoint your tongue with liquid-storax, and you may put a pair of
tongs into your mouth red hot, without hurting yourself, and lick
them till they are cold, by the help of this anointment, and by
preparing your mouth thus, you may take wood coal out of the fire,
and eat them as you would bread, dip them into brimstone-powder,
and the fire will seem more strange, but the sulphur puts out the
coal, and shutting your mouth close puts out the sulphur, and so
they champ the coals and swallow them, which they may do without
offending the body; but if they were bound to eat nothing else, it
would be a very sickly trade; and if you put a piece of lighted
charcoal into your mouths you may suffer a pair of bellows to be a
blowing in your mouth continually, and receive no hurt, but your
mouth must be quickly cleaned, otherwise it will cause a salivation;
it is a very dangerous thing to be done, and although those that
practise it, use all the means they can to prevent danger, yet I never
saw any one of these fire eaters that had a good complexion, the
reason I could give, but it is known to the sons of art: some put
bole-armoniack into this receipt: a cold thing, and spoils the whole
composition, and so leaves out hamitatis and liquid storax; but let
them beware how they use it.

How to walk on a hot iron bar, without danger of


scalding or burning.
Take half an ounce of camphire, dissolve it in two ounces of aqua
vitæ, add to it one ounce of quick-silver, one ounce of liquid storax,
which is the droppings of myrrh, and hinders the camphire from
firing, take also two ounces of hamitatis, a red stone to be had at
the druggists, and when you buy it, beat it to powder in their great
mortar, for it is so very hard, that it cannot be done in a small one;
put this to the afore-mentioned composition, and when you intend
to walk on the bar, you must anoint your feet well therewith, and
you may walk over without danger: by this you may wash your
hands in boiling lead.
How to make a knife leap out of a pot.

When you are in company, and intend to make mirth, have a pot
full of water standing on a table, then take a piece of whale-bone
about three inches long, let it be pretty stiff, it will spring the better;
take also a new stiff card, and fold it down the middle long-ways, cut
a hole through both folds at each end, half an inch or more from the
ends, put one end of the whale-bone in at one end of the card, bend
it like a bow, then put the other end of the whale-bone into the
other end of the card, set this into the pot, with two inches or more
deep in water, then place the handle of your knife upon the
uppermost part of the whale-bone, with the point upwards: use
some words of art, as Presto vet, or Omporte.
Note, I have invented a new instrument to perform this fancy,
which is to be admired by all ingenious persons.
The melting-box.

This melting box is another artificial slight, which is shewn as


above, made in the fashion of a screw, that so the lips may hang
without discovery; as thus, F is the out-part of the box; G the first
in-part. H the second in-part; I a round case made of plush or
leather, with a button on the top, and wide enough to slip on and
off, half in the bottom of the box, F put a small quantity of quick-
silver killed, which may be done with the shavings of pewter, or
fasting spittle; in the second part, which is H, let there be six single
pence, put these in the first or out-most part, then put G to H, and
the box is perfect.
When you go to shew this trick, desire any in the company to
lend you a sixpence, and you will return it safe again; but requesting
withal, that none will meddle with any thing they see, unless you
desire them, lest they prejudice you and themselves; then take the
cup off the box, and bid any one see it and feel it, that there may be
no mistrust, so likewise take the box entire, holding your fore-finger
on the bottom, and your thumb on the upper part, turning it upside
down, say, You see here is nothing; then putting in the sixpence, put
the cup over the box again; as the box stands covered upon the
table, put your hand under the table, using some canting words,
then take off the cup with your fore-finger and thumb, so as you
pinch the innermost box with it, and set it gently on the table; then
put the killed quicksilver out of lower part into your hand, turning
the box with the bottom upward and stirring it about with your
finger, ‘Here you see it melted, now I will put it in again and turn it
into six single pence;’ suddenly take the cap as you took it off,
returning it again, bid them blow on it; then take off the cap as you
did before, only pinching the uppermost lid in it, and setting it upon
the table, hold the box at the top and bottom with your fore-finger
and thumb, then put the six single pence, after they are viewed and
seem to be so, in again, and return the cap as before, saying, Blow
on it if you would have it in the same form you gave it me, then
taking the cup by the button, holding the box as before, put out the
six-pence and return the box into your pocket. This is a very good
slight, if well performed, which is done by often use.

How to light a candle by a glass of cold water, or other


liquor, without the help of fire.
You must take a little piece of phosphorus, about the bigness of
a pin’s head, and with a piece of tallow, stick it on the edge of the
drinking-glass, and then take the candle lighted and blow it out; and
apply it to the glass, it will immediately light. This is the preparation
that Cromwell used to fire off his cannon withal, very amazing to
behold; you may write with it on a paper, some horrible words or
other, and it will appear frightful to the beholders: also, you may
take a piece as big as a pin’s head, and rub it on a piece of paper,
and it will be soon all on a flame.
A trick upon the globe-box.

This is a trick not inferior to the best that is shewn with boxes; it
is a box made of four pieces, and a ball so big as is imagined to be
contained therein: the ball serves in the same nature, as the egg
does in the egg box, only to deceive the hand and eye of the
spectators. This ball, made of wood or ivory, is thrown out of the
box upon the table, for everyone to see that it is substantial, then
putting the ball into the box, and letting the standers-by blow on the
box, taking off the upper shell with your fore-finger and thumb,
there appears another, and of another colour, as red, blue, yellow, or
any variety of colours upon each ball that is so imagined to be,
which indeed is no more than the shell of wood ingeniously turned
and fitted for the box, as you may see in the figures above.
L, the out-shell of the globe taken off the figures; M, N, an inner
shell; O, the cover of the same; P, the other inner shell; Q, the cover
of the same; R, the third shell; S, that which covers it. These globes
may be made with more or less varieties, according to the desire of
the practitioner.

To tell the names of all cards in the pack, before you


see them.
Take a pack of cards, and after you have shuffled them, or let
another shuffle them, lay them down upon the table before you,
with their backs uppermost, then say, ‘Now I will tell you the names
of all the rest of the cards in the pack, except one, before I see
them;’ having said so draw off the uppermost cards, and say, ‘This is
my Hocus Pocus. This is he by whose assistance I shall discover all
the rest of the cards in the pack; I care not what he is, for I can
make any of them serve for the same purpose.’ Then put him to your
mouth, as tho’ you charmed him, and repeat some cramp words;
and taking off the next card from the pack, say, Here is the ——
naming your Hocus Pocus, and having seen him, lay him down.

How to hold four kings in the hand, and by words to


seem to transform them into four aces, and afterwards
to make them all blank cards.
You shall see a juggler take four kings in his hand, and
apparently shew you them, then after some words and charms, he
will throw them down upon the table, taking one of the kings away,
and adding but one other card, then taking them up again, and
blowing upon them, will shew you them transformed into blank
cards, white on both sides, then throwing them down as before, with
their faces downwards, will take them up again, and blowing upon
them, will shew you four aces. This trick, in my mind, is not inferior
to any of the rest, and being not known, will seem very strange to
the beholders, and yet after you know it, you cannot but say the
trick is pretty. Now to do this feat, you must have cards made for the
purpose, half cards we may call them; that is one half kings and the
other half aces, so laying the aces one over the other, nothing but
kings will be seen, and then turning the kings downwards, the four
aces will be seen; but you must have two whole cards, one a king,
to cover one of the aces, or else it will be perceived; and the other
an ace, to lay over the kings, when you mean to shew the aces;
then, when you would make them all blank, lay the cards a little
lower and hide the aces, and they will appear all white. The like you
may make of four knaves, putting upon them the four fives; and so
of the other cards.

To tell or name all the cards in the pack, and yet never
see them.
To do this, you must first privately drop a drop of water or beer
about the bigness of a two-pence upon the table before you, were
you sit, then rest your elbows upon the table so as the cuffs of your
sleeves may meet, and your hands stick up to the brims of your hat;
in this posture your arms will hide the drop of water from the
company; then let any one take the cards and shuffle them, and put
them into your hands; also let them set a candle before you, for this
trick is best done by candle light, then holding the cards in your left
hand, above the brim of your hat, up close to your head, so as the
light of the candle may shine upon the cards, and holding your head
down; so in the drop of water, like a looking-glass, you shall see the
shadow of all the cards before you; draw then the fingers of your
right-hand along upon the cards, as though you felt the spots, name
the cards, and then lay him down. Thus you may lay down all the
cards in the pack, one by one, naming them before you lay them
down, which will seem very strange to the beholders, who will think
that you have felt them out.

To shew one what card he taketh notice of.


Let any man take a card out of the pack, and note him: then take
part of the pack in your hand, and lay the rest down upon the table;
bidding him lay his noted card upon them; then turning your back
towards the company, make as though you were looking over the
cards in your hand, and put any card at the fore-side; and whilst you
are doing this privately, wait the cards being laid out in heaps, to
find what the bottom cards are. Bid any one take four cards of the
same number, viz. 4 aces, 4 duces, 4 trays, 4 fours, or any other
number not exceeding 10, (for he must not take court cards) and lay
them out; then take the remaining cards (if any such there be) and
divide their number by 4, and the quotient shall be the number of
spots of the 4 card: if 12 cards remain, then on each bottom card
ware trays, and if there be no remaining cards, then the four bottom
cards are four aces.
To tell the number of spots on the bottom cards, laid
down on several heaps.
Bid any one take the whole pack of cards in his hand, and having
shuffled them, let him take off the upper card, and having taken
notice of it, let him lay it down upon the table with his face
downwards, and upon it let him lay so many cards, as will make up
the number of the spots on the noted card, 12 e. g. If the card
which the person first took notice of, were a king, queen, or knave,
or a single ten, bid him lay down that card with his face downwards,
calling him ten, upon that card let him lay another, calling him
eleven, and upon another, calling him twelve; then bid him take off
the next uppermost card, saying, what is it? Suppose it were a 9,
and laying it down on another part of the table, calling him 9, upon
him lay another card, calling him 10, and upon him another, calling
him 11, and upon him another, calling him 12; then let him look on
the next uppermost card, and so let him proceed to lay them up in
heaps, in all respects as before, till he has laid out the whole pack;
but if there be any odd cards at the last, I mean, if there is not
enough, to make up the last noted card 12, bid him give them to
you; then to tell him the numbers of all the spots contained in all the
bottom cards of the heaps, do thus, from the number for heaps
subtracted 4, and multiply the remainder by 12, and to the product
add the numbers of those remaining cards, which he gave you, if
any remain, but if there were but four heaps, then those remaining
cards alone, shew the number of spots sought.
Note, That you ought not to see the bottom cards of the heaps,
nor should you see them laid out, or know the number of cards in
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