-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathChapter5.tex
935 lines (769 loc) · 28.2 KB
/
Chapter5.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
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
% LaTeX source for textbook ``How to think like a computer scientist''
% Copyright (C) 1999 Allen B. Downey
% Copyright (C) 2009 Thomas Scheffler
\chapter{Fruitful functions}
\section{Return values}
\index{return}
\index{statement!return}
\index{function!fruitful}
\index{fruitful function}
\index{return value}
\index{void}
\index{function!void}
Some of the built-in functions we have used, like the math
functions, have produced results. That is, the effect of
calling the function is to generate a new value, which we
usually assign to a variable or use as part of an expression.
For example:
\index{math function!exp()}
\index{math function!sin()}
\begin{verbatim}
double e = exp (1.0);
double height = radius * sin (angle);
\end{verbatim}
%
But so far all the functions we have written have been {\bf void}
functions; that is, functions that return no value. When you call
a void function, it is typically on a line by itself, with
no assignment:
\begin{verbatim}
PrintLines (3);
Countdown (n-1);
\end{verbatim}
%
In this chapter, we are going to write functions that return things,
which I will refer to as {\bf fruitful} functions, for want of a
better name. The first example is {\tt area}, which takes a {\tt
double} as a parameter, and returns the area of a circle with the
given radius:
\index{math function!acos()}
\index{pi}
\begin{verbatim}
double Area (double radius)
{
double pi = acos (-1.0);
double area = pi * radius * radius;
return area;
}
\end{verbatim}
%
The first thing you should notice is that the beginning of the
function definition is different. Instead of {\tt void}, which
indicates a void function, we see {\tt double}, which indicates that
the return value from this function will have type {\tt double}.
Also, notice that the last line is an alternate form of the
{\tt return} statement that includes a return value. This
statement means, ``return immediately from this function and
use the following expression as a return value.'' The
expression you provide can be arbitrarily complicated,
so we could have written this function more concisely:
\begin{verbatim}
double Area (double radius)
{
return acos(-1.0) * radius * radius;
}
\end{verbatim}
%
On the other hand, {\bf temporary} variables like {\tt area} often
make debugging easier. In either case, the type of the expression in
the {\tt return} statement must match the return type of the function.
In other words, when you declare that the return type is {\tt double},
you are making a promise that this function will eventually
produce a {\tt double}. If you try to {\tt return} with no
expression, or an expression with the wrong type, the compiler will
take you to task.
\index{temporary variable}
\index{variable!temporary}
Sometimes it is useful to have multiple return
statements, one in each branch of a conditional:
\begin{verbatim}
double AbsoluteValue (double x)
{
if (x < 0)
{
return -x;
}
else
{
return x;
}
}
\end{verbatim}
%
Since these returns statements are in an alternative conditional, only
one will be executed. Although it is legal to have more than one
{\tt return} statement in a function, you should keep in mind that as soon
as one is executed, the function terminates without executing any
subsequent statements.
Code that appears after a {\tt return} statement, or any place else
where it can never be executed, is called {\bf dead code}. Some
compilers warn you if part of your code is dead.
\index{dead code}
If you put return statements inside a conditional, then
you have to guarantee that {\em every possible path} through
the program hits a return statement. For example:
\begin{verbatim}
double AbsoluteValue (double x)
{
if (x < 0)
{
return -x;
}
else if (x > 0)
{
return x;
} /* WRONG!! */
}
\end{verbatim}
%
This program is not correct because if {\tt x} happens to be 0, then
neither condition will be true and the function will end without hitting
a return statement. Unfortunately, many C compilers do not catch
this error. As a result, the program may compile and run, but the
return value when {\tt x==0} could be anything, and will probably
be different in different environments.
\index{absolute value}
\index{error!compile-time}
\index{compile-time error}
By now you are probably sick of seeing compiler errors, but as you
gain more experience, you will realize that the only thing worse
than getting a compiler error is {\em not} getting a compiler error
when your program is wrong.
Here's the kind of thing that's likely to happen: you test {\tt
AbsoluteValue()} with several values of {\tt x} and it seems to work
correctly. Then you give your program to someone else and they run it
in another environment. It fails in some mysterious way, and it
takes days of debugging to discover that the problem is an
incorrect implementation of {\tt AbsoluteValue()}. If only the
compiler had warned you!
\index{compile-time error}
\index{error!compile-time}
\index{debugging}
From now on, if the compiler points out an error in your program, you
should not blame the compiler. Rather, you should thank the compiler
for finding your error and sparing you days of debugging. Some
compilers have an option that tells them to be extra strict and report
all the errors they can find. You should turn this option on all the
time.
\index{math function!fabs()}
As an aside, you should know that there is a function in the
math library called {\tt fabs()} that calculates the absolute
value of a {\tt double} -- correctly.
\section{Program development}
\label{distance}
\index{program development}
At this point you should be able to look at complete C functions
and tell what they do. But it may not be clear yet how to go
about writing them. I am going to suggest one technique that
I call {\bf incremental development}.
\index{incremental development}
\index{program development}
As an example, imagine you want to find the distance between two
points, given by the coordinates $(x_1, y_1)$ and $(x_2, y_2)$. By
the usual definition,
\begin{equation}
distance = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}
\end{equation}
%
The first step is to consider what a {\tt Distance} function
should look like in C. In other words, what are the inputs
(parameters) and what is the output (return value).
In this case, the two points are the parameters, and it is natural to
represent them using four {\tt double}s. The return value is the
distance, which will have type {\tt double}.
Already we can write an outline of the function:
\begin{verbatim}
double Distance (double x1, double y1, double x2, double y2)
{
return 0.0;
}
\end{verbatim}
%
The {\tt return} statement is a placekeeper so that the function will
compile and return something, even though it is not the right answer.
At this stage the function doesn't do anything useful, but it is
worthwhile to try compiling it so we can identify any syntax errors
before we make it more complicated.
In order to test the new function, we have to call it with
sample values. Somewhere in {\tt main()} I would add:
\begin{verbatim}
double dist = Distance (1.0, 2.0, 4.0, 6.0);
printf ("%f\n" dist);
\end{verbatim}
%
I chose these values so that the horizontal
distance is 3 and the vertical distance is 4; that way,
the result will be 5 (the hypotenuse of a 3-4-5 triangle).
When you are testing a function, it is useful to know the right
answer.
Once we have checked the syntax of the function definition, we
can start adding lines of code one at a time. After each
incremental change, we recompile and run the program. That
way, at any point we know exactly where the error must be---in
the last line we added.
The next step in the computation is to find the differences
$x_2 - x_1$ and $y_2 - y_1$. I will store those values in
temporary variables named {\tt dx} and {\tt dy}.
\begin{verbatim}
double Distance (double x1, double y1, double x2, double y2)
{
double dx = x2 - x1;
double dy = y2 - y1;
printf ("dx is %f\n", dx);
printf ("dy is %f\n", dy;
return 0.0;
}
\end{verbatim}
%
I added output statements that will let me check the intermediate
values before proceeding. As I mentioned, I already know that they
should be 3.0 and 4.0.
\index{scaffolding}
When the function is finished I will remove the output statements. Code
like that is called {\bf scaffolding}, because it is helpful for
building the program, but it is not part of the final product.
Sometimes it is a good idea to keep the scaffolding around, but
comment it out, just in case you need it later.
The next step in the development is to square {\tt dx} and {\tt dy}.
We could use the {\tt pow()} function, but it is simpler and
faster to just multiply each term by itself.
\begin{verbatim}
double Distance (double x1, double y1, double x2, double y2)
{
double dx = x2 - x1;
double dy = y2 - y1;
double dsquared = dx*dx + dy*dy;
printf ("d_squared is %f\n", dsquared);
return 0.0;
}
\end{verbatim}
%
Again, I would compile and run the program at this stage
and check the intermediate value (which should be 25.0).
Finally, we can use the {\tt sqrt()} function to compute and
return the result.
\begin{verbatim}
double Distance (double x1, double y1, double x2, double y2)
{
double dx = x2 - x1;
double dy = y2 - y1;
double dsquared = dx*dx + dy*dy;
double result = sqrt (dsquared);
return result;
}
\end{verbatim}
%
Then in {\tt main()}, we should output and check the value of the result.
As you gain more experience programming, you might find yourself
writing and debugging more than one line at a time. Nevertheless,
this incremental development process can save you a lot of
debugging time.
The key aspects of the process are:
\begin{itemize}
\item Start with a working program and make small, incremental
changes. At any point, if there is an error, you will know
exactly where it is.
\item Use temporary variables to hold intermediate values so
you can output and check them.
\item Once the program is working, you might want to remove
some of the scaffolding or consolidate multiple statements into
compound expressions, but only if it does not make the program
difficult to read.
\end{itemize}
\section{Composition}
\index{composition}
As you should expect by now, once you define a new function,
you can use it as part of an expression, and you can build
new functions using existing functions. For example, what if someone
gave you two points, the center of the circle and a point on
the perimeter, and asked for the area of the circle?
Let's say the center point is stored in the variables {\tt xc}
and {\tt yc}, and the perimeter point is in {\tt xp} and
{\tt yp}. The first step is to find the radius of the circle, which
is the distance between the two points. Fortunately, we have
a function, {\tt Distance()}, that does that.
\begin{verbatim}
double radius = Distance (xc, yc, xp, yp);
\end{verbatim}
%
The second step is to find the area of a circle with that
radius, and return it.
\begin{verbatim}
double result = Area (radius);
return result;
\end{verbatim}
%
Wrapping that all up in a function, we get:
\begin{verbatim}
double AreaFromPoints (double xc, double yc, double xp, double yp)
{
double radius = Distance (xc, yc, xp, yp);
double result = Area (radius);
return result;
}
\end{verbatim}
%
The temporary variables {\tt radius} and {\tt area} are
useful for development and debugging, but once the program is
working we can make it more concise by composing
the function calls:
\begin{verbatim}
double AreaFromPoints (double xc, double yc, double xp, double yp)
{
return Area (Distance (xc, yc, xp, yp));
}
\end{verbatim}
\section{Boolean values}
\index{boolean}
\index{value!boolean}
The types we have seen so far can hold very large values. There are a lot
of integers in the world, and even more floating-point numbers.
By comparison, the set of characters is pretty small. Well, many computing
languages implement an even more fundamental type that is even smaller. It is called
{\bf \_Bool}, and the only values in it are {\tt true} and {\tt false}.
Unfortunately, earlier versions of the C standard did not implement boolean as
a separate type, but instead used the integer values 0 and 1 to represent
truth values. By convention 0 represents {\tt false} and 1 represents {\tt true}.
Strictly speaking C interprets any integer value different from 0 as true. This
can be a source of error if you are testing a value to be true by comparing it with {\tt 1}.
%
Without thinking about it, we have been using boolean values in the
last of chapter. The condition inside an {\tt if}
statement is a boolean expression.
Also, the result of a comparison operator is a boolean value.
For example:
\begin{verbatim}
if (x == 5)
{
/* do something*/
}
\end{verbatim}
%
The operator {\tt ==} compares two integers and produces a
boolean value.
\index{operator!comparison}
\index{comparison operator}
Pre C99 has no keywords for the expression of {\tt true} or {\tt false}.
A lot of programs instead are
using C preprocessor definitions anywhere a boolean expression is called for.
For example,
\begin{verbatim}
#define FALSE 0
#define TRUE 1
...
if (TRUE)
{
/* will be always executed */
}
\end{verbatim}
%
%todo: Loop?
is a standard idiom for a loop that should run forever (or
until it reaches a {\tt return} or {\tt break} statement).
\section{Boolean variables}
\index{type!{\tt bool}}
Since boolean values are not supported directly in C, we can not declare
variables of the type boolean.
Instead, programmers typically use the {\tt short} datatype in combination with
preprocessor definitions to store truth values.
\begin{verbatim}
#define FALSE 0
#define TRUE 1
...
short fred;
fred = TRUE;
short testResult = FALSE;
\end{verbatim}
%
The first line is a simple variable declaration;
the second line is an assignment, and the third line is a
combination of a declaration and as assignment,
called an initialization.
\index{initialization}
\index{statement!initialization}
As I mentioned, the result of a comparison operator is a boolean,
so you can store it in a variable
\begin{verbatim}
short evenFlag = (n%2 == 0); /* true if n is even */
short positiveFlag = (x > 0); /* true if x is positive */
\end{verbatim}
%
and then use it as part of a conditional statement later
\begin{verbatim}
if (evenFlag)
{
printf("n was even when I checked it");
}
\end{verbatim}
%
A variable used in this way is called a {\bf flag},
since it flags the presence or absence of some condition.
\index{flag}
\section{Logical operators}
\index{logical operator}
\index{operator!logical}
There are three {\bf logical operators} in C: AND, OR and NOT,
which are denoted by the symbols {\tt \&\&}, {\tt ||} and
{\tt !}. The semantics (meaning) of these operators is similar
to their meaning in English. For example {\tt x > 0 \&\& x < 10}
is true only if {\tt x} is greater than zero AND less than 10.
\index{semantics}
{\tt evenFlag || n\%3 == 0} is true if {\em either} of
the conditions is true, that is, if {\tt evenFlag} is true OR the
number is divisible by 3.
Finally, the NOT operator has the effect of negating or
inverting a bool expression, so {\tt !evenFlag} is true
if {\tt evenFlag} is false; that is, if the number is odd.
\index{nested structure}
Logical operators often provide a way to simplify nested
conditional statements. For example, how would you write
the following code using a single conditional?
\begin{verbatim}
if (x > 0)
{
if (x < 10)
{
printf ("x is a positive single digit.\n");
}
}
\end{verbatim}
\section{Bool functions}
\label{bool}
\index{bool}
\index{function!bool}
It is sometimes appropriate for functions to return {\tt boolean} values just
like any other return type. This is
is especially convenient for hiding complicated tests inside
functions. For example:
\begin{verbatim}
int IsSingleDigit (int x)
{
if (x >= 0 && x < 10)
{
return TRUE;
}
else
{
return FALSE;
}
}
\end{verbatim}
%
The name of this function is {\tt IsSingleDigit()}. It is common
to give such test functions names that sound like yes/no questions.
The return type is {\tt int}, which means that again we need
to follow the agreement that 0 represents {\tt false} and 1
represents {\tt true}. Every return
statement has to follow this convention, again, we are using
preprocessor definitions.
The code itself is straightforward, although it is a bit longer than
it needs to be. Remember that the expression {\tt x >= 0 \&\& x < 10}
is evaluated to a {\tt boolean} value, so there is nothing wrong with returning it
directly, and avoiding the {\tt if} statement altogether:
\begin{verbatim}
int IsSingleDigit (int x)
{
return (x >= 0 && x < 10);
}
\end{verbatim}
%
In {\tt main()} you can call this function in the usual ways:
\begin{verbatim}
printf("%i\n", IsSingleDigit (2));
short bigFlag = !IsSingleDigit (17);
\end{verbatim}
%
The first line outputs the value {\tt true} because 2 is a
single-digit number. Unfortunately, when C outputs {\tt boolean} values, it
does not display the words {\tt TRUE} and {\tt FALSE}, but rather the
integers {\tt 1} and {\tt 0}.
%\footnote{There is a way to fix that
%using the {\tt boolalpha} flag, but it is too hideous to mention.}
The second line assigns the value {\tt true} to {\tt bigFlag}
only if 17 is {\em not} a positive single-digit number.
The most common use of boolean functions is inside conditional
statements
\begin{verbatim}
if (IsSingleDigit (x))
{
printf("x is little\n");
}
else
{
printf("x is big\n");
}
\end{verbatim}
\section {Returning from {\tt main()}}
Now that we know functions that return values, we can look more closely at the
return value of the {\tt main()} function.
It's supposed to return an integer:
\begin{verbatim}
int main (void)
\end{verbatim}
The usual return value from {\tt main()} is 0, which indicates that
the program succeeded at whatever it was supposed to to. If something
goes wrong, it is common to return -1, or some other value that
indicates what kind of error occurred.
\index{header file!stdlib.h}
\index{<stdlib.h>}
\index{EXIT\_SUCCESS}
\index{EXIT\_FAILURE}
The C standard library \texttt{<stdlib.h>} provides two predefined constants {\tt EXIT\_SUCCESS} and {\tt EXIT\_FAILURE}.
We can use these to return a descriptive result from our return statement.
\begin{verbatim}
#include <stdlib.h>
int main (void)
{
return EXIT_SUCCESS; /*program terminated successfully*/
}
\end{verbatim}
%
Of course, you might wonder who this value gets returned to, since
we never call {\tt main()} ourselves. It turns out that when the
operating system executes a program, it starts by calling {\tt main()}
in pretty much the same way it calls all the other functions.
When the program terminates it passes a value back
that tells if the execution was successful or not. The operating system
can use this value to create error reports or even pass this value on
to other programs.
There are even some parameters that can be passed to {\tt main()}
by the system, but we are not going to deal with them for a little
while, so we define {\tt main()} as having no parameters: {\tt int main (void)}.
%\section {More recursion}
%\index{recursion}
%\index{language!complete}
%So far we have only learned a small subset of C, but you
%might be interested to know that this subset is now
%a {\bf complete} programming language, by which I
%mean that anything that can be computed can be expressed in this
%language. Any program ever written could be rewritten
%using only the language features we have used so far (actually, we
%would need a few commands to control devices like the keyboard, mouse,
%disks, etc., but that's all).
%\index{Turing, Alan}
%Proving that claim is a non-trivial exercise first
%accomplished by Alan Turing, one of the first computer scientists
%(well, some would argue that he was a mathematician, but a lot of the
%early computer scientists started as mathematicians). Accordingly, it
%is known as the Turing thesis. If you take a course on the Theory of
%Computation, you will have a chance to see the proof.
%To give you an idea of what you can do with the tools we have learned
%so far, we'll evaluate a few recursively-defined
%mathematical functions. A recursive definition is similar to a
%circular definition, in the sense that the definition contains a
%reference to the thing being defined. A truly circular definition is
%typically not very useful:
%\begin{description}
%\item[frabjuous:] an adjective used to describe
%something that is frabjuous.
%\index{frabjuous}
%\end{description}
%If you saw that definition in the dictionary, you might be
%annoyed. On the other hand, if you looked up the definition
%of the mathematical function {\bf factorial}, you might
%get something like:
%\begin{eqnarray*}
%&& 0! = 1 \\
%&& n! = n \cdot (n-1)!
%\end{eqnarray*}
%(Factorial is usually denoted with the symbol $!$, which is
%not to be confused with the C logical operator {\tt !} which
%means NOT.) This definition says that the factorial of 0 is 1,
%and the factorial of any other value, $n$, is $n$ multiplied
%by the factorial of $n-1$. So $3!$ is 3 times $2!$, which is 2 times
%$1!$, which is 1 times 0!. Putting it all together, we get
%$3!$ equal to 3 times 2 times 1 times 1, which is 6.
%If you can write a recursive definition of something, you can usually
%write a C program to evaluate it. The first step is to decide what
%the parameters are for this function, and what the return type is.
%With a little thought, you should conclude that factorial takes an
%integer as a parameter and returns an integer:
%\begin{verbatim}
% int factorial (int n)
% {
% }
%\end{verbatim}
%%
%If the argument happens to be zero, all we have to do is
%return 1:
%\begin{verbatim}
% int Factorial (int n)
% {
% if (n == 0)
% {
% return 1;
% }
% }
%\end{verbatim}
%%
%Otherwise, and this is the interesting part, we have to make
%a recursive call to find the factorial of $n-1$, and then
%multiply it by $n$.
%\begin{verbatim}
% int Factorial (int n)
% {
% if (n == 0)
% {
% return 1;
% }
% else
% {
% int recurse = Factorial (n-1);
% int result = n * recurse;
% return result;
% }
% }
%\end{verbatim}
%%
%If we look at the flow of execution for this program,
%it is similar to {\tt nLines} from the previous chapter.
%If we call {\tt factorial} with the value 3:
%Since 3 is not zero, we take the second branch and calculate
%the factorial of $n-1$...
%\begin{quote}
%Since 2 is not zero, we take the second branch and calculate
%the factorial of $n-1$...
%\begin{quote}
%Since 1 is not zero, we take the second branch and calculate
%the factorial of $n-1$...
%\begin{quote}
%Since 0 {\em is} zero, we take the first branch and return
%the value 1 immediately without making any more recursive
%calls.
%\end{quote}
%The return value (1) gets multiplied by {\tt n}, which is 1,
%and the result is returned.
%\end{quote}
%The return value (1) gets multiplied by {\tt n}, which is 2,
%and the result is returned.
%\end{quote}
%\noindent The return value (2) gets multiplied by {\tt n}, which is 3,
%and the result, 6, is returned to {\tt main}, or whoever
%called {\tt Factorial (3)}.
%\index{stack}
%\index{diagram!state}
%\index{diagram!stack}
%Here is what the stack diagram looks like for this sequence of
%function calls:
%\vspace{0.1in}
%\centerline{\epsfig{figure=figs/stack3.eps}}
%\vspace{0.1in}
%%
%The return values are shown being passed back up the stack.
%Notice that in the last instance of {\tt factorial}, the local
%variables {\tt recurse} and {\tt result} do not exist because
%when {\tt n=0} the branch that creates them does not execute.
%\section{Leap of faith}
%\index{leap of faith}
%Following the flow of execution is one way to read programs, but as
%you saw in the previous section, it can quickly become labarynthine.
%An alternative is what I call the ``leap of faith.'' When you come to
%a function call, instead of following the flow of execution, you
%{\em assume} that the function works correctly and returns the
%appropriate value.
%In fact, you are already practicing this leap of faith
%when you use built-in functions. When you call {\tt cos}
%or {\tt exp}, you don't examine the implementations of
%those functions. You just assume that they work, because the people
%who wrote the built-in libraries were good programmers.
%Well, the same is true when you call one of your own functions.
%For example, in Section~\ref{bool} we wrote a function called
%{\tt IsSingleDigit} that determines whether a number is between
%0 and 9. Once we have convinced ourselves that this function
%is correct---by testing and examination of the code---we can
%use the function without ever looking at the code again.
%The same is true of recursive programs. When you get to the recursive
%call, instead of following the flow of execution, you should {\em
%assume} that the recursive call works (yields the correct result), and
%then ask yourself, ``Assuming that I can find the factorial of $n-1$,
%can I compute the factorial of $n$?'' In this case, it is clear that
%you can, by multiplying by $n$.
%Of course, it is a bit strange to assume that the function works
%correctly when you have not even finished writing it, but that's why
%it's called a leap of faith!
%\section{One more example}
%\index{factorial}
%In the previous example I used temporary variables to spell out the
%steps, and to make the code easier to debug, but I could have saved a
%few lines:
%\begin{verbatim}
% int Factorial (int n)
% {
% if (n == 0)
% {
% return 1;
% }
% else
% {
% return n * Factorial (n-1);
% }
% }
%\end{verbatim}
%%
%From now on I will tend to use the more concise version, but
%I recommend that you use the more explicit version while you
%are developing code. When you have it working, you can
%tighten it up, if you are feeling inspired.
%After {\tt Factorial}, the classic example of a recursively-defined
%mathematical function is {\tt Fibonacci}, which has the
%following definition:
%\begin{eqnarray*}
%&& fibonacci(0) = 1 \\
%&& fibonacci(1) = 1 \\
%&& fibonacci(n) = fibonacci(n-1) + fibonacci(n-2);
%\end{eqnarray*}
%%
%Translated into C, this is
%\begin{verbatim}
% int Fibonacci (int n)
% {
% if (n == 0 || n == 1)
% {
% return 1;
% }
% else
% {
% return Fibonacci (n-1) + Fibonacci (n-2);
% }
% }
%\end{verbatim}
%%
%If you try to follow the flow of execution here, even for fairly small
%values of {\tt n}, your head explodes. But according to the leap of
%faith, if we assume that the two recursive calls (yes, you can make
%two recursive calls) work correctly, then it is clear that we get the
%right result by adding them together.
\section{Glossary}
\begin{description}
\item[return type:] The type of value a function returns.
\item[return value:] The value provided as the result of a function
call.
\item[dead code:] Part of a program that can never be executed,
often because it appears after a {\tt return} statement.
\item[scaffolding:] Code that is used during program development
but is not part of the final version.
\item[void:] A special return type that indicates a void function;
that is, one that does not return a value.
\item[boolean:] A value or variable that can take on one of
two states, often called $true$ and $false$. In C, boolean
values are mainly stored in variables of type {\tt short} and
preprocessor statements are used to define the states.
\item[flag:] A variable that records
a condition or status information.
\item[comparison operator:] An operator that compares two values
and produces a boolean that indicates the relationship between the
operands.
\item[logical operator:] An operator that combines boolean values
in order to test compound conditions.
\index{return type}
\index{return value}
\index{dead code}
\index{scaffolding}
\index{void}
\index{bool}
\index{operator!conditional}
\index{operator!logical}
\end{description}
\section{Exercises}
\setcounter{exercisenum}{0}
\input{exercises/Exercise_5_english}