Programming In C Volume 1 Basic Data Structures And Program Statements Xingni Zhou pdf download
Programming In C Volume 1 Basic Data Structures And Program Statements Xingni Zhou pdf download
https://ebookbell.com/product/programming-in-c-volume-1-basic-
data-structures-and-program-statements-xingni-zhou-50339330
https://ebookbell.com/product/ms-course-10266a-programming-in-c-with-
microsoft-visual-studio-2010-trainer-edition-
volume-1-microsoft-2113632
https://ebookbell.com/product/art-of-computer-programming-
volume-4a-combinatorial-algorithms-part-1-1st-edition-donald-e-
knuth-2226790
https://ebookbell.com/product/programming-in-c-volume-2-composite-
data-structures-and-modularization-50338946
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
https://ebookbell.com/product/thinking-in-c-volume-2-practical-
programming-us-ed-bruce-eckel-1136612
https://ebookbell.com/product/programming-in-c-object-oriented-
features-laxmisha-rai-editor-china-science-publishing-media-ltd-
editor-51127748
https://ebookbell.com/product/programming-in-c-for-engineering-and-
science-1st-edition-nyhoff-55234332
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) ----
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
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
www.degruyter.com
Preface
Ideas of the book
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]
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
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
Xingni Zhou
xnzhou@xidian.edu.cn
In Chang’an, midsummer 2020
Contents
Preface V
Introduction IX
Structure of content XI
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
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
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
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
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.
https://doi.org/10.1515/9783110692327-001
2 1 Introduction to programs
Case Study 1
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
Case Study 3
Flow of baking bread
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
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.
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.
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.
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.
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.
Washing Sequential
case 1 structure
Start
Soak
Wash
Rinse
Spin-dry
End
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
Start
End
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.
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
Start
Consider all
clothes load
Clothes load
situations
Basic washing
program
End
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
Rinse
End
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.
End
Start
Problem analysis
T Has F
decision
T F
Has repetition
End
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.”
Branch Loop
Operation 1 Operation 1
Operation 2 Operation 2
...
Rectangle
process Operation n Operation n
symbol
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.
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.
Test and
execute
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.
Execute
Operation set A and test
do
T {
Condition Operation set A
} while (condition)
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
Program
Programming language
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.
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
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.
Computer
Internal
memory (RAM)
Processing
Information
processing
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
1 6
Program Input Output
RAM Result output
device device
Data
5 3 2
CPU
Processor Control unit
4 Data stream
Control signal
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 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)
External
memory
(Hard disks)
Data
Data in programs are information computers can store and process
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
Input/output devices-related issues include how data are input and output. Note
that external memory is deemed input/output device in programming.
Description of
processing Algorithm
process • Description of processing process – algorithms
• Involves form of expression, method of description
and design principles
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 confederacy, 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 confeder‐
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 confederacy, 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 confederate, 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 confederate 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.
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.
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 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 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.
ebookbell.com