-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathChapter2.tex
More file actions
702 lines (571 loc) · 21.2 KB
/
Copy pathChapter2.tex
File metadata and controls
702 lines (571 loc) · 21.2 KB
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
% LaTeX source for textbook ``How to think like a computer scientist''
% Copyright (C) 1999 Allen B. Downey
% Copyright (C) 2009 Thomas Scheffler
\setcounter{chapter}{1}
\chapter{Variables and types}
\section{More output}
\index{output}
\index{statement!output}
As I mentioned in the last chapter, you can put as many statements as
you want in {\tt main()}. For example, to output more than one line:
\begin{verbatim}
#include <stdio.h>
#include <stdlib.h>
/* main: generate some simple output */
int main (void)
{
printf ("Hello World.\n"); /* output one line */
printf ("How are you?\n"); /* output another line */
return (EXIT_SUCCESS);
}
\end{verbatim}
%
As you can see, it is legal to put comments at the
end of a line, as well as on a line by themselves.
\index{String}
\index{type!String}
The phrases that appear in quotation marks are called {\bf strings},
because they are made up of a sequence (string) of letters. Actually,
strings can contain any combination of letters, numbers, punctuation
marks, and other special characters.
\index{newline}
Often it is useful to display the output from multiple output
statements all on one line. You can do this by leaving out
the {\tt $\backslash$n} from the first {\tt printf}:
\begin{verbatim}
int main (void)
{
printf ("Goodbye, ");
printf ("cruel world!\n");
return (EXIT_SUCCESS);
}
\end{verbatim}
%
In this case the output appears on a single line as
{\tt Goodbye, cruel world!}. Notice that there is a space
between the word ``Goodbye,'' and the second quotation mark.
This space appears in the output, so it affects the behavior
of the program.
Spaces that appear outside of quotation marks generally do
not affect the behavior of the program. For example, I
could have written:
\begin{verbatim}
int main(void)
{
printf("Goodbye, ");
printf("cruel world!\n");
return(EXIT_SUCCESS);
}
\end{verbatim}
%
This program would compile and run just as well as the original.
The breaks at the ends of lines (newlines) do not affect
the program's behavior either, so I could have written:
\begin{verbatim}
int main(void){printf("Goodbye, ");printf("cruel world!\n");
return(EXIT_SUCCESS);}
\end{verbatim}
%
That would work, too, although you have probably noticed that
the program is getting harder and harder to read. Newlines and
spaces are useful for organizing your program visually, making
it easier to read the program and locate syntax errors.
\section{Values}
\index{value}
\index{type}
Computer programs operate on values stored in
computer memory.
A value ---like a letter or
a number--- is one of the fundamental things that a program manipulates.
The only values we have
manipulated so far are the strings we have been outputting, like
{\tt "Hello, world."}. You (and the compiler) can identify
these string values because they are enclosed in quotation marks.
%constant values
There are different kinds of values, including integers and characters.
It is important for the program to know exactly what kind of value
is manipulated because not all manipulations will make sense on all
values.
We therefore distinguish between different {\bf types} of values.
%Example 'a' + 'a'
An integer is a whole number like 1 or 17. You can output
integer values in a similar way as you output strings:
\begin{verbatim}
printf("%i\n", 17);
\end{verbatim}
%
When we look at the \texttt{printf()} statement more closely, we
notice that the value we are outputting no longer appears
inside the quotes, but behind them separated by comma.
The string is still there, but now contains a {\tt \%i} instead of
any text.
The {\tt \%i} a placeholder that tells the \texttt{printf()} command
to print an integer value. Several such placeholders exist
for different data types and formatting options of the output.
We will see the next one just now.
A character value is a letter or digit or punctuation mark
enclosed in single quotes, like {\tt 'a'} or {\tt '5'}.
You can output character values in a similar way:
\begin{verbatim}
printf("%c\n", '}');
\end{verbatim}
%
This example outputs a single closing curly-bracket on a line
by itself. It uses the {\tt \%c} placeholder to signify the output of a character
value.
It is easy to confuse different types of values, like {\tt "5"}, {\tt
'5'} and {\tt 5}, but if you pay attention to the punctuation, it
should be clear that the first is a string, the second is a character
and the third is an integer. The reason this distinction is important
should become clear soon.
\section {Variables}
\index{variable}
\index{value}
One of the most powerful features of a programming language is the
ability to manipulate values through the use of {\bf variables}. So far
the values that we have used in our statements where fixed to what
was written in the statement. Now we will use a variable as a named
location that stores a value.
Just as there are different types of values (integer, character,
etc.), there are different types of variables. When you create a new
variable, you have to declare what type it is. For example, the
character type in C is called {\tt char}. The following statement
creates a new variable named {\tt fred} that has type {\tt char}.
\begin{verbatim}
char fred;
\end{verbatim}
%
This kind of statement is called a {\bf declaration}.
The type of a variable determines what kind of values it can
store. A {\tt char} variable can contain characters, and it should
come as no surprise that {\tt int} variables can store integers.
Contrary to other programming languages, C does not have a
dedicated variable type for the storage of string values. We will see in
a later chapter how string values are stored in C.
%but we
%are going to skip that for now (see Chapter~\ref{strings}).
\index{declaration}
\index{statement!declaration}
To create an integer variable, the syntax is
\begin{verbatim}
int bob;
\end{verbatim}
%
where {\tt bob} is the arbitrary name you choose to identify the
variable. In general, you will want to make up variable names
that indicate what you plan to do with the variable. For
example, if you saw these variable declarations:
\begin{verbatim}
char first_letter;
char last_letter;
int hour, minute;
\end{verbatim}
%
you could probably make a good guess at what values
would be stored in them. This example
also demonstrates the syntax for declaring multiple variables
with the same type: {\tt hour} and {\tt minute}
are both integers ({\tt int} type).
ATTENTION: The older C89 standard allows variable declarations
only at the beginning of a block of code. It is therefore necessary
to put variable declarations before any other statements,
even if the variable itself is only needed much later in your program.
\section{Assignment}
\index{assignment}
\index{statement!assignment}
Now that we have created some variables, we would like to
store values in them. We do that with an {\bf assignment
statement}.
\begin{verbatim}
first_letter = 'a'; /* give first_letter the value 'a' */
hour = 11; /* assign the value 11 to hour */
minute = 59; /* set minute to 59 */
\end{verbatim}
%
This example shows three assignments, and the comments show
three different ways people sometimes talk about assignment
statements. The vocabulary can be confusing here, but the
idea is straightforward:
\begin{itemize}
\item When you declare a variable, you create a named storage location.
\item When you make an assignment to a variable, you give it a value.
\end{itemize}
A common way to represent variables on paper is to draw a box
with the name of the variable on the outside and the value
of the variable on the inside. This kind of figure is called
a {\bf state diagram} because is shows what state each
variable is in (you can think of it as the variable's ``state of
mind'').
This diagram shows the effect of the three assignment statements:
%\vspace{0.1in}
%\centerline{\epsfig{figure=figs/assign.eps}}
%\vspace{0.1in}
\setlength{\unitlength}{1mm}
\begin{picture}(20,17)
\put(7,12){\large \texttt{first\_letter}}
\put(46,12){\large \texttt{hour}}
\put(74,12){\large \texttt{minute}}
\put(10,0){\framebox(20,10){{\large \textsf{a}}}}
\put(40,0){\framebox(20,10){{\large \textsf{11}}}}
\put(70,0){\framebox(20,10){{\large \textsf{59}}}}
\end{picture}
When we assign values to variables, we have to make sure that
the assigned value correspondents to the type of the variable.
In C a variable has to have the same type as the
value you assign. For example, you cannot store a string in
an {\tt int} variable. The following statement generates a compiler
warning:
\begin{verbatim}
int hour;
hour = "Hello."; /* WRONG !! */
\end{verbatim}
%
This rule is sometimes a source of confusion, because there are many
ways that you can convert values from one type to another, and C
sometimes converts things automatically. But for now you should
remember that as a general rule variables and values have the same
type, and we'll talk about special cases later.
Another source of confusion is that some strings {\em look}
like integers, but they are not. For example,
the string {\tt "123"}, which is made up of the
characters {\tt 1}, {\tt 2} and {\tt 3}, is not
the same thing as the {\em number} {\tt 123}.
This assignment is illegal:
\begin{verbatim}
minute = "59"; /* WRONG!! */
\end{verbatim}
%
\section{Outputting variables}
\label{output variables}
You can output the value of a variable using the same commands
we used to output simple values.
\begin{verbatim}
int hour, minute;
char colon;
hour = 11;
minute = 59;
colon = ':';
printf ("The current time is ");
printf ("%i", hour);
printf ("%c", colon);
printf ("%i", minute);
printf ("\n");
\end{verbatim}
%
This program creates two integer variables named {\tt hour} and {\tt
minute}, and a character variable named {\tt colon}. It assigns
appropriate values to each of the variables and then uses a series
of output statements to generate the following:
\begin{verbatim}
The current time is 11:59
\end{verbatim}
When we talk about ``outputting a variable,'' we mean outputting the
{\em value} of the variable. The name of a variable only has significance for
the programmer. The compiled program no longer contains a human readable
reference to the variable name in your program.
The \texttt{ printf()} command is capable of outputting several variables
in a single statement. To do this, we need to put placeholders
in the so called \emph{format string}, that indicate the position where the variable value will
be put. The variables will be inserted in the order of their appearance in
the statement. It is important to observe the right order and type for the variables.
By using a single output statement, we can make the previous program more
concise:
\begin{verbatim}
int hour, minute;
char colon;
hour = 11;
minute = 59;
colon = ':';
printf ("The current time is %i%c%i\n", hour, colon, minute);
\end{verbatim}
%
On one line, this program outputs a string, two integers and a character. Very impressive!
\section{Keywords}
\index{keyword}
A few sections ago, I said that you can make up any name you
want for your variables, but that's not quite true. There
are certain words that are reserved in C because they are
used by the compiler to parse the structure of your program,
and if you use them as variable names, it will get confused.
These words, called {\bf keywords}, include {\tt int},
{\tt char}, {\tt void} and many more.
\vskip 1em
\setlength{\fboxsep}{6pt}
\begin{center}
\begin{boxedminipage}[c]{.9\linewidth}
\begin{center}
\begin{multicols}{5}[\underline{Reserved keywords in the C language}]
\begin{verbatim}
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
inline
int
long
register
restrict
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
_Bool
_Complex
_Imaginary
\end{verbatim}
\end{multicols}
\end{center}
\end{boxedminipage}
\end{center}
\vskip 1em
The complete list of keywords is included in the C Standard, which
is the official language definition adopted by the the International
Organization for Standardization (ISO) on September 1, 1998.
%You can download a copy electronically from
%
%\begin{verbatim}
% http://www.ansi.org/
%\end{verbatim}
%
Rather than memorize the list, I would suggest that you
take advantage of a feature provided in many development
environments: code highlighting. As you type, different
parts of your program should appear in different colors. For
example, keywords might be blue, strings red, and other code
black. If you type a variable name and it turns blue, watch
out! You might get some strange behavior from the compiler.
\section{Operators}
\label{operators}
\index{operator}
{\bf Operators} are special symbols that are used to represent
simple computations like addition and multiplication. Most
of the operators in C do exactly what you would expect them
to do, because they are common mathematical symbols. For
example, the operator for adding two integers is {\tt +}.
The following are all legal C expressions whose meaning is
more or less obvious:
\begin{verbatim}
1+1 hour-1 hour*60+minute minute/60
\end{verbatim}
%
{\bf Expressions} can contain both variables
names and values. In each case the name of the variable is
replaced with its value before the computation is performed.
\index{expression}
Addition, subtraction and multiplication all do what you
expect, but you might be surprised by division. For example,
the following program:
\begin{verbatim}
int hour, minute;
hour = 11;
minute = 59;
printf ("Number of minutes since midnight: %i\n", hour*60 + minute);
printf ("Fraction of the hour that has passed: %i\n", minute/60);
\end{verbatim}
%
would generate the following output:
\begin{verbatim}
Number of minutes since midnight: 719
Fraction of the hour that has passed: 0
\end{verbatim}
%
The first line is what we expected, but the second line is
odd. The value of the variable {\tt minute} is 59, and
59 divided by 60 is 0.98333, not 0. The reason for the
discrepancy is that C is performing {\bf integer division}.
\index{type!int}
\index{integer division}
\index{arithmetic!integer}
\index{division!integer}
\index{operand}
When both of the {\bf operands} are integers (operands are the things
operators operate on), the result must also be an integer,
and by definition integer division always rounds {\em down},
even in cases like this where the next integer is so close.
A possible alternative in this case is to calculate a percentage
rather than a fraction:
\begin{verbatim}
printf ("Percentage of the hour that has passed: ");
printf ("%i\n", minute*100/60);
\end{verbatim}
%
The result is:
\begin{verbatim}
Percentage of the hour that has passed: 98
\end{verbatim}
%
Again the result is rounded down, but at least now the answer
is approximately correct. In order to get an even more accurate
answer, we could use a different type of variable, called
floating-point, that is capable of storing fractional values.
We'll get to that in the next chapter.
\section{Order of operations}
\index{precedence}
\index{order of operations}
When more than one operator appears in an expression the order
of evaluation depends on the rules of {\bf precedence}. A
complete explanation of precedence can get complicated, but
just to get you started:
\begin{itemize}
\item Multiplication and division happen before
addition and subtraction. So {\tt 2*3-1} yields 5, not 4, and {\tt
2/3-1} yields -1, not 1.
%(remember that in integer division {\tt 2/3} is 0).
\item If the operators have the same precedence they are evaluated
from left to right. So in the expression {\tt minute*100/60},
the multiplication happens first, yielding {\tt 5900/60}, which
in turn yields {\tt 98}. If the operations had gone from right
to left, the result would be {\tt 59*1} which is {\tt 59}, which
is wrong.
\item Any time you want to override the rules of precedence (or
you are not sure what they are) you can use parentheses. Expressions
in parentheses are evaluated first, so {\tt 2*(3-1)} is 4.
You can also use parentheses to make an expression easier to
read, as in {\tt (minute*100)/60}, even though it doesn't
change the result.
\end{itemize}
\section{Operators for characters}
\index{character operator}
\index{operator!character}
Interestingly, the same mathematical operations that work on
integers also work on characters. For example,
\begin{verbatim}
char letter;
letter = 'a' + 1;
printf ("%c\n", letter);
\end{verbatim}
%
outputs the letter {\tt b}. Although it is syntactically legal
to multiply characters, it is almost never useful to do it.
Earlier I said that you can only assign integer values to
integer variables and character values to character variables,
but that is not completely true. In some cases, C converts
automatically between types. For example, the following is
legal.
\begin{verbatim}
int number;
number = 'a';
printf ("%i\n", number);
\end{verbatim}
%
The result is 97, which is the number that is used internally
by C to represent the letter {\tt 'a'}. However, it is
generally a good idea to treat characters as characters, and
integers as integers, and only convert from one to the other
if there is a good reason.
Automatic type conversion is an example of a common problem in designing a
programming language, which is that there is a conflict between {\bf
formalism}, which is the requirement that formal languages should have
simple rules with few exceptions, and {\bf convenience}, which is the
requirement that programming languages be easy to use in practice.
More often than not, convenience wins, which is usually good for
expert programmers, who are spared from rigorous but unwieldy
formalism, but bad for beginning programmers, who are often baffled
by the complexity of the rules and the number of exceptions. In this
book I have tried to simplify things by emphasizing the rules and
omitting many of the exceptions.
\section{Composition}
\index{composition}
\index{expression}
So far we have looked at the elements of a programming
language---variables, expressions, and statements---in
isolation, without talking about how to combine them.
One of the most useful features of programming languages
is their ability to take small building blocks and
{\bf compose} them. For example, we know how to multiply
integers and we know how to output values; it turns out we can
do both at the same time:
\begin{verbatim}
printf ("%i\n", 17 * 3);
\end{verbatim}
%
Actually, I shouldn't say ``at the same time,'' since in reality
the multiplication has to happen before the output, but
the point is that any expression, involving numbers, characters,
and variables, can be used inside an output statement. We've
already seen one example:
\begin{verbatim}
printf ("%i\n", hour * 60 + minute);
\end{verbatim}
%
You can also put arbitrary expressions on the right-hand
side of an assignment statement:
\begin{verbatim}
int percentage;
percentage = (minute * 100) / 60;
\end{verbatim}
%
This ability may not seem so impressive now, but we will see
other examples where composition makes it possible
to express complex computations neatly and concisely.
WARNING: There are limits on where you can use certain
expressions; most notably, the left-hand side of an assignment
statement has to be a {\em variable} name, not an expression.
That's because the left side indicates the storage location
where the result will go. Expressions
do not represent storage locations, only values. So the
following is illegal: {\tt minute + 1 = hour;}.
\section{Glossary}
\begin{description}
\item[variable:] A named storage location for values. All
variables have a type, which determines which values it can
store.
\item[value:] A letter, or number, or other thing that can be
stored in a variable.
\item[type:] The meaning of values. The types
we have seen so far are integers ({\tt int} in C) and characters ({\tt
char} in C).
\item[keyword:] A reserved word that is used by the compiler
to parse programs. Examples we have seen include {\tt int},
{\tt void} and {\tt char}.
\item[statement:] A line of code that represents a command or
action. So far, the statements we have seen are declarations,
assignments, and output statements.
\item[declaration:] A statement that creates a new variable and
determines its type.
\item[assignment:] A statement that assigns a value to a variable.
\item[expression:] A combination of variables, operators and
values that represents a single result value. Expressions also
have types, as determined by their operators and operands.
\item[operator:] A special symbol that represents a simple
computation like addition or multiplication.
\item[operand:] One of the values on which an operator operates.
\item[precedence:] The order in which operations are evaluated.
\item[composition:] The ability to combine simple
expressions and statements into compound statements and expressions
in order to represent complex computations concisely.
\index{variable}
\index{value}
\index{type}
\index{keyword}
\index{statement}
\index{assignment}
\index{expression}
\index{operator}
\index{operand}
\index{composition}
\end{description}
\section{Exercises}
\setcounter{exercisenum}{0}
\input{exercises/Exercise_2_english}