-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsection4-Booleans,while.tex
319 lines (254 loc) · 13.9 KB
/
section4-Booleans,while.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
\section{Loops and booleans}
How would you write a program to add up a series of numbers?
If you knew that there were, say, four numbers, you might write
this program:
\VerbatimInput[frame=single,label=Example]{src/s3Example.groovy}
But a similar program to add up 100 numbers would be very long.
More seriously, each program would need to be tailor-made for a particular
number of numbers. It would be better if we could write one program
to handle \emph{any} series of numbers. We need a \emph{loop}.
One way to create a loop is to use the keyword \texttt{while}.
For example:
\VerbatimInput[frame=single,label=Example]{src/s3Example2.groovy}
It is not essential to indent the lines inside the loop, but it makes the
program easier to read and it is a good habit to get into.
Having initialized the variable \texttt{num} to zero, the program checks
whether the value of \texttt{num} is less than 100. It is, so it
enters the loop. Inside the loop, it adds 5 to the value of
\texttt{num} and then outputs this value (so the first thing that
appears on the screen is a \texttt{5}). Then it goes back to the
\texttt{while} and checks whether the value of \texttt{num} is less than
100. The current value of \texttt{num} is 5, which is less than 100,
so it enters the loop again. It adds 5 to \texttt{num}, so
\texttt{num} takes the value 10, and then outputs this value. It goes back
to the \texttt{while}, checks whether 10 is less than 100 and enters
the loop again. It carries on doing this with \texttt{num} getting
larger each time round the loop. Eventually \texttt{num} has the
value 95. As 95 is still less than 100, it enters the loop again, adds 5 to
\texttt{num} to make it 100 and outputs this number. Then it goes
back to the \texttt{while} and this time sees that \texttt{num} is not
less than 100. So it stops looping and goes on to the line after the
end of the loop. (In the case of this program, there are no more
lines, so it finishes.) The output of this program is the numbers 5,
10, 15, 20 and so on up to 95, 100.
Note the use of curly braces to mark the start and end of the loop.
Each time round the loop the program does everything inside the curly braces.
When it decides not to execute the loop again, it jumps to the point
beyond the closing brace.
What would happen if the \texttt{while} line of this program was
\texttt{while (num != 99)}?
The value of \texttt{num} would eventually reach 95. The computer would
decide that 95 was not equal to 99 and would go round the loop again.
It would add 5 to \texttt{num,} making 100.
It would now decide that 100 was not equal to 99 and would go round the
loop again. Next time \texttt{num} would have the value 105, then 110,
then 115 and so on. The value of \texttt{num} would never be equal to 99
and the computer would carry on for ever. This is an example of
an \emph{infinite loop}.
Note that the computer makes the test \emph{before} it enters the loop.
What would happen if the \texttt{while} line of this program was
\texttt{while (num > 0)}? \texttt{num} begins with the value zero and the computer would first
test whether this value was greater than zero. Zero is not greater than
zero, so it would not enter the loop. It would skip straight to the end
of the loop and finish, producing no output.
% It is not essential to indent the lines inside the loop, but it makes the
% program easier to read and it is a good habit to get into.
\subsection*{Exercise A}
Write a program that outputs the squares of all the numbers from 1 to
10, i.e. the output will be the numbers 1, 4, 9, 16 and so on up to 100.
\subsection{Booleans (true/false expressions)}
So far we have just used integer and string variables. But we can
have variables of other types and, specifically, we can have
\emph{boolean} variables\footnote{The word ``boolean'' was coined in honour of an
Irish mathematician of the nineteenth century called \emph{George Boole}}.
In Groovy, these are variables of type \texttt{boolean}.
A variable of type \texttt{boolean} does not hold numbers;
it can hold just the values \texttt{true} and \texttt{false}. We
might declare and initialize a boolean variable thus:
\begin{Verbatim}
boolean positive = true
\end{Verbatim}
Note that we do not have quote marks around the word \texttt{true}.
The word \texttt{true}, without quote marks, is not a string; it's the name of a
boolean value. Contrast it with:
\begin{Verbatim}
String stringvar = "true"
\end{Verbatim}
\texttt{stringvar} is a String variable which is being initialized
with the four-character string ``\texttt{true}''; we could assign any
other string to \texttt{stringvar}. By contrast, \texttt{positive}
is a boolean variable and we cannot assign strings to it.
It can hold only the values \texttt{true} or \texttt{false}.
You have already met boolean expressions. They are also called conditional
expressions and they are the sort of expression you have in brackets
after \texttt{if} or \texttt{while}. When you evaluate a boolean expression,
you get the value \texttt{true} or \texttt{false} as the result.
Consider the kind of integer assignment statement with which you are
now familiar:
\begin{Verbatim}
num = count + 5
\end{Verbatim}
The expression on the right-hand side, the \texttt{count + 5}, is an
integer expression. That is, when we evaluate it, we get an integer value
as the result. And of course an integer value is exactly the right kind of
thing to assign to an integer variable.
Now consider a similar-looking boolean assignment statement:
\begin{Verbatim}
positive = num >= 0
\end{Verbatim}
The expression on the right-hand side, the \texttt{num >= 0}, is a
boolean expression. That is, when we evaluate it, we get a boolean value
(true/false) as the result. And of course a boolean value is exactly the
right kind of thing to assign to a boolean variable. You can achieve
the same effect by the following more long-winded statement:
\begin{Verbatim}
if (num >= 0) {
positive = true
} else {
positive = false
}
\end{Verbatim}
The variable \texttt{positive} now stores a simple fact about the value of
\texttt{num} at this point in the program. (The value of \texttt{num} might
subsequently change, of course, but the value of \texttt{positive} will not
change with it.) If, later in the program, we wish to test
the value of \texttt{positive}, we need only write
\begin{Verbatim}
if (positive)
\end{Verbatim}
You can write \texttt{if (positive == true)} if you prefer, but the
\texttt{== true}
is redundant. \texttt{positive} itself is either true or false.
%Once the computer has evaluated \texttt{positive}
%(established whether it is true or false) there is nothing more to do.
We can also write
\begin{Verbatim}
if (!positive)
\end{Verbatim}
(pronounced \emph{if not positive}) that is exactly the same as \texttt{if
(positive == false)}. If \texttt{positive} is true, then not
\texttt{positive} is false, and vice-versa.
Boolean variables are often called \emph{flags}. The idea is that
% , leaving aside subtleties such as half-mast,
a flag has basically two states
--- either it's flying or it isn't.
So far we have constructed simple boolean expressions using the operators
introduced in the last chapter --- \texttt{(x == y), (s >= t)} and so on ---
now augmented with negation~(\verb+!+).
We can make more complex boolean expressions by joining simple ones
with the operators \emph{and} (\verb!&&!) and \emph{or} (\texttt{||}). For example,
we can express ``if x is a non-negative odd number'' as
\verb+if (x >= 0 && x \% 2 == 1)+. We can express ``if the name begins
with an A or an E'' as \texttt{if (name.substring(0,1) == "A" ||
name.substring(0,1) == "E")}. The rules for evaluating \emph{and}
and \emph{or} are as follows:
\vspace{1em}
\begin{tabular}{|l|lcr||lcr|}
\hline
& left & \verb!&&! & right & left & \verb+||+ & right\\
\hline
\hline
1 & true & \textbf{true} & true&true&\textbf{true}&true\\
2 & true & \textbf{false} & false&true&\textbf{true}&false\\
3 & false & \textbf{false} & true&false&\textbf{true}&true\\
4 & false & \textbf{false} & false&false&\textbf{false}&false\\
\hline
\end{tabular}
\vspace{1em}
Taking line 2 as an example, this says that, given that you have two simple
boolean expressions joined by \emph{and} and that the one on the left is
true while the one on the right is false, the whole thing is false. If,
however, you had the same two simple expressions joined by \emph{or}, the
whole thing would be true. As you can see, \emph{and} is true if and
only if both sides are true, otherwise it's false; \emph{or} is false
if and only if both sides are false, otherwise it's true.
\subsection*{Exercise B}
Given that \texttt{x} has the value 5, \texttt{y} has the value 20,
and \texttt{s} has the value ``\texttt{Birkbeck}'', decide whether these
expressions are true or false:
\begin{verbatim}
(x == 5 && y == 10)
(x < 0 || y > 15)
(y % x == 0 and s.length() == 8)
(s.substring(1,3) == "Bir" || x / y > 0)
\end{verbatim}
\subsection{Back to loops}
Returning to the problem of adding up a series of numbers, have a
look at this program:
\VerbatimInput[frame=single,label=Example]{src/s3Example3.groovy}
If we want to input a series of numbers, how will the program know
when we have put them all in? That is the tricky part, which accounts
for the added complexity of this program.
The \texttt{boolean} variable
\texttt{finished} is being used to help us detect when there are no more
numbers. It is initialized to \texttt{false}. When the computer detects
that the last number (``0'') is introduced, it will be set to \texttt{true}.
When \texttt{finished} is true, it means that we have finished reading in
the input. The \texttt{while} loop begins by testing whether \texttt{finished}
is true or not. If \texttt{finished} is not true, there is some more input
to read and we enter the loop. If \texttt{finished} is true, there are
no more numbers to input and we skip to the end of the loop.
The variable \texttt{total} is initialized to zero.
Each time round the loop, the computer reads a new value into \texttt{num}
and adds it to \texttt{total}. So \texttt{total} holds the total of all
the values input so far.
Actually the program only adds \texttt{num} to \texttt{total} if a (non-zero)
number has been entered.
% The user will signal that there are no more numbers by keying in a special
% character. (On Unix this is a Control-D; on PCs it is usually a Control-Z.
% If this is gobbledygook to you, just imagine that the user strikes a special
% key on the keyboard.)
If the user enters something other than an integer
--- perhaps a letter or a punctuation mark ---
then the parsing of the input will fail
and the program will stop, giving an error message.
% If the program is expecting an integer
% and instead receives something like ``abc'' or ``W'' or ``**!'', the input will fail.
% We can test whether the input has finished with the line \texttt{if (sc.hasNext())}.
% If this is false, then there is no more input available and we set \texttt{finished} to \texttt{true}
% in order to terminate the loop.
A real-life program ought not to respond to a user error by aborting
with a terse error message, though regrettably many of them do.
However, dealing with this problem properly would make this little program
more complicated than I want it to be at this stage.
\textbf{You have to take some care in deciding whether a line should go in the
loop or outside it}. This program, for example, is only slightly different
from the one above but it will perform differently:
\VerbatimInput[frame=single,label=Example]{src/s3Example4.groovy}
It resets \texttt{total} to zero \emph{each time round the loop.} So
\texttt{total} gets set to zero,
has a value added to it, then gets set to zero, has another value added to
it, then gets set to zero again, and so on. When the program finishes,
\texttt{total} does not hold the total of all the numbers, just the value
zero.
Here is another variation:
\VerbatimInput[frame=single,label=Example]{src/s3Example5.groovy}
This one has the \texttt{print} line inside the loop, so it outputs the value
of \texttt{total} each time round the loop. If you keyed in the numbers
4, 5, 6, 7 and 8, then, instead of just getting the total (30) as the output,
you would get 4, 9, 15, 22 and then 30.
\subsection*{Exercise C}
Write a program that reads a series of numbers, ending with 0, and then tells you how
many numbers you have keyed in (other than the last 0). For example, if you keyed in the
numbers~5, -10, 50, 22, -945, 12, 0 it would output ``You have entered 6
numbers.''.
% \subsection{System libraries}
% The purpose of libraries is to provide the programmer with extensions
% to the language which can be pulled in, as and when needed.
% Some libraries, known as the standard libraries, are provided with every
% Groovy implementation. Other libraries can be created for special purposes.
% One team of programmers might produce a library of routines for another
% team of programmers to use. When teams of programmers divide up the
% work on a large program in this way, it is all too easy
% for programmers in team A to choose a name for some item in their library
% and for programmers in team B to choose
% the same name for some quite unrelated item elsewhere in the program.
% This can be a serious nuisance. To help contain the problem, Groovy
% provides \emph{packages}. Team A declares one namespace and team B
% declares another. Now it doesn't matter if they accidentally choose the
% same name. Team B can still use names from A's package, but they have to
% tell the compiler specifically which names they are going to use.
%%% Local Variables:
%%% mode: latex
%%% TeX-master: "main"
%%% End: