-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathch08.tex
More file actions
1207 lines (935 loc) · 39.7 KB
/
ch08.tex
File metadata and controls
1207 lines (935 loc) · 39.7 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
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
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\chapter{Recursive Methods}
\index{iterative}
\index{recursive}
Up to this point, we've been using \java{while} and \java{for} loops whenever we've needed to repeat something.
Methods that use iteration are called {\bf iterative}.
They are straight-forward, but sometimes there are more elegant solutions.
In this chapter, we explore one of the most magical things that a method can do: invoke {\em itself} to solve a smaller version of the {\em same} problem.
A method that invokes itself is called {\bf recursive}.
\section{Recursive Void Methods}
\label{recursion}
\index{countdown}
%slr: 11/17/19
Consider the following iterative example from Section~\ref{The_while_statement}:
% height = 130 + 11 * num_lines
\begin{trinket} [230] {Blastoff.java}
public class Blastoff {
public static void main(String[] args) {
int n = 3;
while (n > 0) {
System.out.println(n);
n = n - 1;
}
System.out.println("Blastoff!");
}
}
\end{trinket}
We can rewrite this using \emph{recursion}. In the following trinket, the method \java{countdown} calls \emph{itself}:
% height = 130 + 11 * num_lines
\begin{trinket} [280] {RecursiveBlastoff.java}
public class RecursiveBlastoff {
public static void main(String[] args) {
countdown(3);
}
public static void countdown(int n) {
if (n == 0) { //'base case' - ends the sequence of recursive calls
System.out.println("Blastoff!");
} else {
System.out.println(n);
countdown(n - 1);
}
}
}
\end{trinket}
%\begin{code}
%public static void countdown(int n) {
% if (n == 0) {
% System.out.println("Blastoff!");
% } else {
% System.out.println(n);
% countdown(n - 1);
% }
%}
%\end{code}
%slr: end 11/17/19
The name of the method is \java{countdown}; it takes a single integer as a parameter.
If the parameter is zero, it displays the word ``Blastoff''.
Otherwise, it displays the number and then invokes itself, passing \java{n - 1} as the argument.
What happens if we invoke \java{countdown(3)} from \java{main}?
\vspace{-1ex}
\begin{quote}
The execution of \java{countdown} begins with \java{n == 3}, and since \java{n} is not zero, it displays the value 3, and then invokes itself...
\begin{quote}
The execution of \java{countdown} begins with \java{n == 2}, and since \java{n} is not zero, it displays the value 2, and then invokes itself...
\begin{quote}
The execution of \java{countdown} begins with \java{n == 1}, and since \java{n} is not zero, it displays the value 1, and then invokes itself...
\begin{quote}
The execution of \java{countdown} begins with \java{n == 0}, and since \java{n} is zero, it displays the word ``Blastoff!'' and then returns.
\end{quote}
The \java{countdown} that got \java{n == 1} returns.
\end{quote}
The \java{countdown} that got \java{n == 2} returns.
\end{quote}
The \java{countdown} that got \java{n == 3} returns.
\end{quote}
\vspace{-1ex}
And then you're back in \java{main}.
So the total output looks like:
\begin{stdout}
3
2
1
Blastoff!
\end{stdout}
%slr: 11/17/19
The java classes (i.e. programs) \java{Blastoff} and \java{RecursiveBlastoff} produce the same result, but with very different strategies. It can be shown that any iterative algorithm can be written as a recursive one and conversely. In practice, some tasks can be performed much more easily with one scheme than the other.
%slr: end 11/17/19
As a second example, we'll rewrite the methods \java{newLine} and \java{threeLine} from Section~\ref{adding_methods}.
Here they are again:
\begin{code}
public static void newLine() {
System.out.println();
}
public static void threeLine() {
newLine();
newLine();
newLine();
}
\end{code}
\index{newline}
Although these methods work, they would not help if we wanted to display two newlines, or maybe 100.
A more general \textbf{iterative} alternative would be:
\begin{code}
public static void nLines(int n) {
for(int i = 0; i < n; i++) {
System.out.println();
}
}
\end{code}
And a more general \textbf{recursive} alternative would be:
\begin{code}
public static void nLines(int n) {
if (n == 0) { //'base case' - ends the sequence of recursive calls
return;
} else {
System.out.println();
nLines(n - 1);
}
}
\end{code}
This recursive method takes an integer, \java{n}, as a parameter and displays \java{n} newlines.
The structure is similar to the \java{countdown} method in class RecursiveCountdown above.
As long as $n$ is greater than zero, it displays a newline and then invokes itself to display $(n-1)$ additional newlines.
The total number of newlines is $1 + (n - 1)$, which is just what we wanted: $n$.
%slr: 11/17/19
Here is a complete Java trinket class:
% height = 130 + 11 * num_lines
\begin{trinket} [300] {RecursiveNewLines.java}
public class RecursiveNewLines {
public static void main(String[] args) {
System.out.println("Here come 3 newlines:");
nLines(3);
System.out.println("Goodbye!");
}
public static void nLines(int n) {
if (n == 0) { //'base case' - ends the sequence of recursive calls
return;
} else {
System.out.println();
nLines(n - 1);
}
}
}
\end{trinket}
\textbf{Section Exercises:}
\begin{enumerate}
\item Modify the trinket so that it prints a character (perhaps a period or an asterisk) on each of the newlines.
\item Modify the trinket so that it produces the same output, but with base case condition \java{n == 1} instead of \java{n == 0}.
\end{enumerate}
%slr: end 11/17/19
\section{Recursive Stack Diagrams}
\index{stack diagram}
\index{diagram!stack}
In Section~\ref{stack}, we used a stack diagram to represent the state of a program during a method invocation.
The same kind of diagram can make it easier to interpret a recursive method.
Remember that every time a method gets called, Java creates a new frame that contains the method's parameters and variables.
Figure~\ref{fig.stack2} is a stack diagram for \java{countdown}, called with \java{n == 3}.
\begin{figure}[!ht]
\begin{center}
\includegraphics{figs/stack2.pdf}
\caption{Stack diagram for the \java{countdown} program.}
\label{fig.stack2}
\end{center}
\end{figure}
By convention, the frame for \java{main} is at the top, and the stack of other frames grows down.
That way, we can draw stack diagrams on paper without needing to guess how far they will grow.
The frame for \java{main} is empty because \java{main} does not have any variables.
(It has the parameter \java{args}, but since we're not using it, we left it out of the diagram.)
\index{base case}
There are four frames for \java{countdown}, each with a different value for the parameter \java{n}.
The last frame, with \java{n == 0}, is called the {\bf base case}.
It does not make a recursive call, so there are no more frames below it.
\index{StackOverflowError}
\index{exception!StackOverflow}
If there is no base case in a recursive method, or if the base case is never reached, the stack would grow forever---at least in theory.
In practice, the size of the stack is limited.
If you exceed the limit, you get a \java{StackOverflowError}.
For example, here is an example of a recursive method without a base case:
%slr: 11/17/19
%\begin{code}
%public static void forever(String s) {
% System.out.println(s);
% forever(s);
%}
%\end{code}
% height = 130 + 11 * num_lines
\begin{trinket} [230] {InfiniteRecursiveMethod.java}
public class InfiniteRecursiveMethod {
public static void main(String[] args) {
forever("and again,");
}
public static void forever(String s) {
System.out.println(s);
forever(s);
}
}
\end{trinket}
\index{call stack}
Run the program and see what happens. This recursive method repeatedly displays the given string since there is no base case ending the recursion - an infinite recursion. The program does terminate, however, when the stack overflows and an exception is thrown.
\textbf{Section Exercises:}
\begin{enumerate}
\item Modify the trinket so that it is no longer infinite.
\end{enumerate}
%slr: end 11/17/19
\section{Value-Returning Methods}
\label{factorial}
%\index{Turing complete}
%\index{language!complete}
%
%\index{Turing, Alan}
%\index{Church, Alonzo}
%
%Now that we have methods that return values, we have a {\bf Turing complete} programming language.
%That means Java can compute anything computable, for any reasonable definition of ``computable''.
%This idea was developed by Alonzo Church and Alan Turing, so it is known as the Church-Turing thesis.
%You can read more about it at \url{https://en.wikipedia.org/wiki/Turing_thesis}.
To give you an idea of what you can do with the tools we have learned, let's look at methods that evaluate recursively-defined mathematical functions which therefor return a value.
A recursive definition is similar to a ``circular'' definition, in the sense that the definition refers to the thing being defined.
Of course, a truly circular definition is not very useful:
\begin{quote}
{\bf recursive:} \\
An adjective used to describe a method that is recursive.
\end{quote}
\index{recursion}
If you saw that definition in the dictionary, you might be annoyed.
Then again, if you search for ``recursion'' on Google, it displays ``Did you mean: recursion'' as an inside joke.
People fall for that link all the time.
\index{factorial}
Many mathematical functions are defined recursively, because that is often the simplest way.
For example, the {\bf factorial} of an integer $n$, which is written $n!$, is defined like this:
%
\begin{eqnarray*}
&& 0! = 1 \\
&& n! = n \cdot(n-1)!
\end{eqnarray*}
%
Don't confuse the mathematical symbol $!$, which means {\em factorial}, with the Java operator \java{!}, which means {\em not}.
This definition says that \java{factorial(0)} is \java{1}, and \java{factorial(n)} is \java{n * factorial(n - 1)}.
So \java{factorial(3)} is \java{3 * factorial(2)}; \java{factorial(2)} is \java{2 * factorial(1)}; \java{factorial(1)} is \java{1 * factorial(0)}; and \java{factorial(0)} is \java{1}.
Putting it all together, we get \java{3 * 2 * 1 * 1}, which is 6.
If you can formulate a recursive definition of something, you can easily write a Java method to evaluate it.
The first step is to decide what the parameters and return type are.
Since factorial is defined for integers, the method takes an \java{int} as a parameter and returns an \java{int}.
%So here's a good starting place:
\begin{code}
public static int factorial(int n) {
return 0; // stub
}
\end{code}
Next, we think about the base case.
If the argument happens to be zero, we return 1.
\begin{code}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return 0; // stub
}
}
\end{code}
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{code}
public static int factorial(int n) {
if (n == 0) {
return 1; //base case
} else {
int recurse = factorial(n - 1);
int result = n * recurse;
return result;
}
}
\end{code}
To illustrate what is happening, we use the temporary variables \java{recurse} and \java{result}.
In each method call, \java{recurse} stores the factorial of $n - 1$, and \java{result} stores the factorial of $n$.
%slr: 11/19/19
The trinket below is a complete, executable program illustrating a recursive algorithm for computing 3!:
% height = 130 + 11 * num_lines
\begin{trinket} [280] {RecursiveFactorial.java}
public class RecursiveFactorial {
public static void main(String[] args) {
System.out.println("3! = " + factorial(3));
}
public static int factorial(int n) {
if (n == 0) {
return 1; //base case
} else {
int recurse = factorial(n - 1);
int result = n * recurse;
return result;
}
}
}
\end{trinket}
%slr: end 11/19/19
The flow of execution for this program is similar to \java{countdown} from Section~\ref{recursion}.
If we invoke \java{factorial} with the value 3:
\vspace{-1ex}
\begin{quote}
Since 3 is not zero, we skip the first branch and calculate the factorial of $n-1$...
\begin{quote}
Since 2 is not zero, we skip the first branch and calculate the factorial of $n-1$...
\begin{quote}
Since 1 is not zero, we skip the first 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 invocations.
\end{quote}
The return value (1) gets multiplied by \java{n}, which is 1, and the result is returned.
\end{quote}
The return value (1) gets multiplied by \java{n}, which is 2, and the result is returned.
\end{quote}
The return value (2) gets multiplied by \java{n}, which is 3, and the result, 6, is returned to whatever invoked \java{factorial(3)}.
\end{quote}
\vspace{-1ex}
\index{stack diagram}
\index{diagram!stack}
Figure~\ref{fig.stack3} shows what the stack diagram looks like for this sequence of method invocations.
The return values are shown being passed up the stack.
Notice that \java{recurse} and \java{result} do not exist in the last frame, because when \java{n == 0} the code that declares them does not execute.
\begin{figure}[!ht]
\begin{center}
\includegraphics{figs/stack3.pdf}
\caption{Stack diagram for the \java{factorial} method.}
\label{fig.stack3}
\end{center}
\end{figure}
%slr: 11/21/19 omit leap of faith section - incorporate into previous section
%\section{The Leap of Faith}
%\label{leap_of_faith}
%
%\index{leap of faith}
%
%Following the flow of execution is one way to read programs, but it can quickly become overwhelming.
%Another way to understand recursion is the {\bf leap of faith}:
%when you come to a method invocation, instead of following the flow of execution, you {\em assume} that the method works correctly and returns the appropriate value.
%
%In fact, you are already practicing this leap of faith when you use methods in the Java library.
%When you invoke \java{Math.cos} or \java{System.out.println}, you don't think about the implementations of those methods.
%You just assume that they work properly.
%
%The same is true of other methods.
%For example, consider the method from Section~\ref{boolmeth} that determines whether an integer has only one digit:
%
%\begin{code}
%public static boolean isSingleDigit(int x) {
% return x > -10 && x < 10;
%}
%\end{code}
%
%Once you convince yourself that this method is correct---by examining and testing the code---you can just use the method without ever looking at the implementation again.
%
%Recursive methods are no different.
%When you get to a recursive call, don't think about the flow of execution.
%Instead, {\em assume} that the recursive call produces the desired result.
%
%For example, ``Assuming that I can find the factorial of $n-1$, can I compute the factorial of $n$?''
%Yes you can, by multiplying by $n$.
%slr: end 11/21/19 omit leap of faith section
Here's an implementation of \java{factorial} without use of the temporary variables \java{recurse} and \java{result}:
\begin{code}
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
\end{code}
Notice how similar this version is to the original mathematical definition:
%There is essentially a one-to-one correspondence.
%
\begin{eqnarray*}
&& 0! = 1 \\
&& n! = n \cdot(n-1)!
\end{eqnarray*}
%
%Of course, it is strange to assume that the method works correctly when you have not finished writing it.
%But that's why it's called a leap of faith!
Following the flow of execution of a recursive method is one way to understand it, but this can become overwhelming. Another way to understand a recursive method is to read and understand it the same way we read the recursive definition itself.
%\section{Fibonacci Sequence}
\label{fibonacci}
\index{fibonacci}
As another example consider the recursively-defined Fibonacci sequence, a function which has the following definition:
%
\begin{eqnarray*}
&& fibonacci(1) = 1 \\
&& fibonacci(2) = 1 \\
&& fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)
\end{eqnarray*}
%
Notice that each Fibonacci number is the sum of the two preceding Fibonacci numbers. Thus the terms of the sequence are: 1, 1, 2, 3, 5, 8, 13, 21, ...
We see from the definition of the Fibonacci sequence that the \textbf{base case} is evaluating the function at \java{1} or at \java{2}:
\begin{code}
public static int fibonnacci(int n) {
if (n == 1 || n == 2) {
return 1; //base case(s)
} else {
return 0; //stub for recursive case
}
}
\end{code}
What about the recursive case? If n neither 1 nor 2, we want to invoke the recursive method \textbf{twice}, once at \java{n-1} and once at \java{n-2} and add the results per the definition above. Translated into Java, this function is:
\begin{code}
public static int fibonacci(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
\end{code}
If you try to follow the flow of execution here, even for small values of \java{n}, your head will explode. Each call to the method \java{fibonacci} may result in \textbf{two more} invocations of \java{fibonacci}!
But it is clear, looking at the definition, that our implementation is correct once we understand recursive method calls.
Here is a complete trinket implentation for computing a term of the Fibonacci sequence:
% height = 130 + 11 * num_lines
\begin{trinket} [270] {Fibonacci.java}
public class Fibonacci {
public static void main(String[] args) {
System.out.printf("5th term of the Fibonacci sequence is %d\n", fibonacci(5));
}
public static int fibonacci(int n) {
if (n == 1 || n == 2) {
return 1; //base case
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
}
\end{trinket}
Run the trinket and see what you get.
\textbf{Section Exercises:}
\begin{enumerate}
\item Modify the trinket above containing the class \java{RecursiveFactorial} so that it in no longer uses the temporary variables \java{recurse} and \java{result}. Verify that it works correctly.
\item Modify the trinket above containing the class \java{Fibonacci} to compute and display the first 10 terms of the sequence.
\item Modify the trinket above containing the class \java{Fibonacci} to compute the 50th term of the sequence. (Be patient!) What happens? Why?
\item Modify the trinket above containing the class \java{Fibonacci} to compute the term \textit{iteratively} rather than \textit{recursively}.
\end{enumerate}
\section{Counting Up Recursively}
\label{countup}
The \java{countdown} example in Section~\ref{recursion} has three parts: (1) it checks the base case, (2) it displays something, and (3) it makes a recursive call.
What do you think happens if you reverse steps (2) and (3), making the recursive call {\em before} displaying? Run the trinket below and see:
%slr: 11/22/19
% height = 130 + 11 * num_lines
\begin{trinket} [280] {CountUp.java}
public class CountUp {
public static void main(String[] args) {
countup(3);
}
public static void countup(int n) {
if (n == 0) {
System.out.println("Blastoff!");
} else {
countup(n - 1);
System.out.println(n);
}
}
}
\end{trinket}
%\begin{code}
%public static void countup(int n) {
% if (n == 0) {
% System.out.println("Blastoff!");
% } else {
% countup(n - 1);
% System.out.println(n);
% }
%}
%\end{code}
%slr: end 11/22/19
The stack diagram is the same as before, and the method is still called $n$ times.
But now the \java{System.out.println} happens just before each recursive call returns.
As a result, it counts {\em up} instead of down:
\begin{stdout}
Blastoff!
1
2
3
\end{stdout}
Keep this in mind for the next example, which displays numbers in binary.
\section{Binary Number System}
\label{binary}
You are probably aware that computers can only store 1's and 0's.
That's because processors and memory are made up of billions of tiny on-off switches.
The value 1 means a switch is on; the value 0 means a switch is off.
All types of data, whether integer, floating-point, text, audio, video, or something else, are represented by 1's and 0's.
\index{binary}
Fortunately, we can represent any integer as a {\bf binary} number.
The following table shows the first eight numbers in binary and decimal.
\begin{table}[!ht]
\begin{center}
\begin{tabular}{|c|c|}
\hline
Binary & Decimal \\
\hline
0 & 0 \\
\hline
1 & 1 \\
\hline
10 & 2 \\
\hline
11 & 3 \\
\hline
100 & 4 \\
\hline
101 & 5 \\
\hline
110 & 6 \\
\hline
111 & 7 \\
\hline
\end{tabular}
\caption{The first eight binary numbers.}
\label{tab:binary}
\end{center}
\end{table}
%In the decimal system, each part of a number is referred to as a %``digit''.
%For example, the number 456 has three digits.
%In the binary system, each part of a number is referred to as a ``bit''.
%The number 10111 in binary has five bits.
%When you hear the phrase ``64-bit computer'', it means that the %processors and memory use 64 bits to store integers.
%That is where the limits for data types like \java{int} and \java{long} %come from.
% ABD: I think we can leave bits out of the discussion, and just talk
% about different written representations of the same number.
In decimal there are 10 digits, and the written representation of numbers is based on powers of 10.
For example, the number 456 has 4 in the 100's place, 5 in the 10's place, and 6 in the 1's place.
So the value is 400 + 50 + 6.
\begin{center}
\begin{tabular}{|c|c|c|}
\hline
4 & 5 & 6 \\
\hline
$10^2$ & $10^1$ & $10^0$ \\
\hline
\end{tabular}
\end{center}
In binary there are 2 digits, and the written representation of numbers is based on powers of 2.
For example, the number 10111 has 1 in the 16's place, 0 in the 8's place, 1 in the 4's place, 1 in the 2's place, and 1 in the 16's place.
So the value is 16 + 0 + 4 + 2 + 1, which is 23 in decimal.
\begin{center}
\begin{tabular}{|c|c|c|c|c|}
\hline
1 & 0 & 1 & 1 & 1 \\
\hline
$2^4$ & $2^3$ & $2^2$ & $2^1$ & $2^0$ \\
\hline
\end{tabular}
\end{center}
To get the digits of a decimal number, we can use repeated division.
For example, if we divide 456 by 10, we get 45 with remainder 6.
The remainder is the rightmost digit of 456.
If we divide the result again, we get 4 with remainder 5.
The remainder is the second rightmost digit of 456.
And if we divide again, we get 0 with remainder 4.
The remainder is the third rightmost digit of 456, and the result, 0, tells us that we're done.
We can do the same thing in binary if we divide by two.
When you divide by two, the remainder is the right-most digit, either 0 or 1.
If you divide the result again, you get the second rightmost digit.
If you keep going, and write down the remainders, you'll have your number in binary.
\begin{stdout}
23 / 2 is 11 remainder 1
11 / 2 is 5 remainder 1
5 / 2 is 2 remainder 1
2 / 2 is 1 remainder 0
1 / 2 is 0 remainder 1
\end{stdout}
Reading these remainders from bottom to top, 23 in binary is 10111.
\section{Recursive Binary Method}
Now, to display a number in binary we can combine the algorithm from the previous section and the ``count up'' pattern from Section~\ref{countup}.
Here is a recursive method that displays any positive integer in binary:
%slr: 11/22/19
\begin{code}
public static void displayBinary(int value) {
if (value == 0) {
return; //base case
} else {
displayBinary(value / 2); //recursive call
System.out.print(value % 2); //print afterwards
}
}
\end{code}
Here is a shorter version of the method that is equivalent:
\begin{code}
public static void displayBinary(int value) {
if (value > 0) {
displayBinary(value / 2); //recursive call
System.out.print(value % 2); //print afterwards
}
}
\end{code}
If \java{value} is zero, this shorter version of \java{displayBinary} does nothing (that's the base case).
If the argument is positive, the method divides it by two and calls \java{displayBinary} recursively.
When the recursive call returns, the method displays one digit of the result and returns (again).
Figure~\ref{fig.stack4} illustrates this process.
\index{stack diagram}
\index{diagram!stack}
\begin{figure}[!ht]
\begin{center}
\includegraphics[width=190pt]{figs/stack4.pdf}
\caption{Stack diagram for the \java{displayBinary} method.}
\label{fig.stack4}
\end{center}
\end{figure}
The leftmost digit is near the bottom of the stack, so it gets displayed first.
The rightmost digit, near the top of the stack, gets displayed last.
%slr: 11/22/19
After invoking \java{displayBinary}, we use \java{println} to complete the output as shown in the trinket below:
%\begin{code}
%displayBinary(23); // output is 10111
%System.out.println();
%\end{code}
% height = 130 + 11 * num_lines
\begin{trinket} [270] {Binary.java}
public class Binary {
public static void main(String[] args) {
displayBinary(23);
System.out.println();
}
public static void displayBinary(int value) {
if (value > 0) {
displayBinary(value / 2); //recursive call
System.out.print(value % 2); //print afterwards
}
}
}
\end{trinket}
Run the trinket to verify we obtain the result \java{10111}.
\section{Two Recursion Examples (from CodingBat)}
In the past several chapters you've seen methods, conditions, loops, strings, arrays, and recursion.
A great resource for practicing all of these concepts is \url{https://codingbat.com/}.
\index{CodingBat}
CodingBat is a free website of programming problems developed by Nick Parlante, a Computer Science lecturer at Stanford University.
As you work on these problems, CodingBat saves your progress (if you create an account).
To conclude this chapter, we consider two problems in the {\sf Recursion-1} section of CodingBat.
One of them deals with strings, and the other deals with arrays.
Both of them have the same recursive idea: check the base case, look at the current index, and recursively handle the rest.
The first problem is available at \url{https://codingbat.com/prob/p118230}:
\begin{quote}
\textbf{Recursion-1 ~noX}
Given a string, recursively compute a new string where all the \java{'x'} chars have been removed.
\ttfamily
noX("xaxb") $\rightarrow$ "ab" \\
noX("abc") $\rightarrow$ "abc" \\
noX("xx") $\rightarrow$ ""
\end{quote}
When solving recursive problems, it helps to think about the base case first.
The base case is the easiest version of the problem; for \java{noX}, it's the empty string.
If the argument is an empty string, there are no {\tt x}'s to be removed.
\begin{code}
if (str.length() == 0) {
return "";
}
\end{code}
% NOTE: Some people like isEmpty(), but I think this is the right
% idiom for our purposes
% https://www.techiedelight.com/check-string-empty-or-null-java/
Next comes the more difficult part.
To solve a problem recursively, you need to think of a simpler instance of the same problem.
For \java{noX}, it's removing all the {\tt x}'s from a shorter string.
So let's split the string into two parts, the first letter and the rest. Since we know the string has length greater than 0, we are assured we can do this:
\begin{code}
char first = str.charAt(0);
String rest = str.substring(1);
\end{code}
Now we can make a recursive call to remove the {\tt x}'s from {\tt rest}:
\begin{code}
String recurse = noX(rest);
\end{code}
That takes care of {\tt rest} and places the result into {\tt recurse},
To take care of {\tt first} we have two possibilities: if it happens to be an {\tt x}, we're done; we just have to return {\tt recurse}. Otherwise, we have to concatenate {\tt first} and {\tt recurse}. Here's the {\tt if} statement we need.
\begin{code}
if (first == 'x') {
return recurse;
} else {
return first + recurse;
}
\end{code}
%slr: 11/22/19
%You can run this solution on CodingBat by pasting these snippets into the provided method definition.
Here is a complete Java class trinket with a stubbed version of the method \java{noX()}:
% height = 130 + 11 * num_lines
\begin{trinket} [270] {NoX.java}
public class NoX {
public static void main(String[] args) {
String s = noX("xaxb");
System.out.println(s);
}
public static String noX(String str) {
if (str.length() == 0) {
return ""; //empty String
} else {
return ""; //stub for recursive case
}
}
}
\end{trinket}
Complete the implementation of the \java{noX()} method and test your code. This is section exercise 1 below.
The second problem is available at \url{https://codingbat.com/prob/p135988}:
\begin{quote}
\textbf{Recursion-1 ~array11}
Given an array of ints, compute recursively the number of times that the value 11 appears in the array.
\ttfamily
array11([1, 2, 11], 0) $\rightarrow$ 1 \\
array11([11, 11], 0) $\rightarrow$ 2 \\
array11([1, 2, 3, 4], 0) $\rightarrow$ 0
\end{quote}
This problem uses the convention of passing the index as an argument. In this way, we can pass the entire array and the index in each recursive call instead of computing and passing a subarray.
The base case is when we've reached the end of the array. At that point, we know there are no more {\tt 11}'s.
\begin{code}
if (index >= nums.length) { //at the end of the array
return 0;
}
\end{code}
Next we look at the current array element (based on the given index), and check if it's an {\tt 11}.
After that, we can recursively check the rest of the array.
Similar to the noX problem, we look at only one array entry per method call.
\begin{code}
int recurse = array11(nums, index + 1); //recursive call with rest of array
if (nums[index] == 11) {
return recurse + 1; //increment the count of 11s
} else {
return recurse;
}
\end{code}
%slr: 11/22/19
%Again, you can run this solutions on CodingBat by pasting the snippets into the method definition.
Here is a complete Java class trinket with a stubbed version of the method \java{array11()}:
% height = 130 + 11 * num_lines
\begin{trinket} [290] {Elevens.java}
public class Elevens {
public static void main(String[] args) {
int a = {0, 23, -4, 11, 1, 11, 35};
int numElevens = array11(a, 0);
System.out.printf("There are %d elevens in the array\n", numElevens);
}
public static int array11(int[] nums, int index) {
if (index >= nums.length) {
return 0; //empty String
} else {
return 0; //stub for recursive case
}
}
}
\end{trinket}
Complete the implementation of the \java{array11()} method and test your code. This is section exercise 2 below.
%slr: end 11/22/19
\index{Java Tutor}
To see how these solutions actually work, you might find it helpful to step through them with a debugger (see Appendix~\ref{debugger}) or Java Tutor (\url{https://thinkjava.org/javatutor}).
Then try solving other CodingBat problems on your own.
Learning to think recursively is an important part of learning to think like a computer scientist.
Many algorithms can be written concisely with recursive methods that perform computations on the way down, on the way up, or both.
\textbf{Section Exercises:}
\begin{enumerate}
\item Complete the implementation of the recursive method in the trinket above containing the class \java{NoX}. Verify that it works correctly.
\item Complete the implementation of the recursive method in the trinket above containing the class \java{Elevens}. Verify that it works correctly.
\end{enumerate}
\section{Vocabulary}
\begin{description}
%\term{void method}
%A method that does not return a value.
%\term{value method}
%A method that returns a value.
\term{iterative}
A method or algorithm that repeats steps using one or more loops.
\term{recursive}
A method or algorithm that invokes itself one or more times with different arguments.
%\term{recursion}
%The process of invoking (and restarting) the same method that is currently executing.
\term{base case}
A condition that causes a recursive method {\em not} to make another recursive call.
%\term{Turing complete}
%A programming language that can implement any theoretically possible algorithm.
\term{factorial}
The product of all the integers up to and including a given integer.
%\term{leap of faith}
%A way to read recursive programs by assuming that the recursive call works, rather than following the flow of execution.
\term{binary}
A system that uses only zeros and ones to represent numbers.
Also known as ``base 2''.
\end{description}
\section{Exercises}
The code for this chapter is in the {\tt ch08} directory of {\tt ThinkJavaCode2}.
See page~\pageref{code} for instructions on how to download the repository.
Before you start the exercises, we recommend that you compile and run the examples.
If you have not already read Appendix~\ref{JUnit}, now might be a good time.
It describes JUnit, a standard framework for writing test code.
\begin{exercise} %%V6 Ex5.5
The purpose of this exercise is to take a problem and break it into smaller problems, and to solve the smaller problems by writing simple methods.
Consider the first verse of the song ``99 Bottles of Beer'':
\begin{quote}
99 bottles of beer on the wall,\\
99 bottles of beer,\\
ya' take one down, ya' pass it around,\\
98 bottles of beer on the wall.
\end{quote}