2. Functions
Overview.
In this chapter, we consider a concept that has as profound an impact on control flow as do conditionals and loops: the function, which allows us to transfer control back and forth between different pieces of code. Functions are important because they allow us to clearly separate tasks within a program and because they provide a general mechanism that enables us to reuse code.- 2.1 Static Methods introduces the Java mechanism (the static method) for implementing functions.
- 2.2 Libraries and Clients describes how to group related static methods into libraries to enable modular programming.
- 2.3 Recursion considers the idea of a function calling itself. This possiblility is known as recursion.
- 2.4 Percolation presents a case study that uses Monte Carlo simulation to study a natural model known as percolation.
Java programs in this chapter.
REF PROGRAM DESCRIPTION 2.1.1 Newton.java create a function for computing the square root function 2.1.2 Gaussian.java implement functions related to the Gaussian distribution 2.1.3 Coupon.java design a modular program for coupon collector 2.1.4 PlayThatTune.java synthesize more realistic sound using harmonics 2.2.1 StdRandom.java create a library to generate random numbers 2.2.2 StdArrayIO.java create a library to read and show 1D and 2D arrays 2.2.3 IFS.java simulate an iterated function system 2.2.4 StdStats.java create a library to analyze statistics 2.2.5 StdStats.java create a library to plot data values 2.2.6 Bernoulli.java verify the Gaussian approximation to the binomial distribution 2.3.1 Euclid.java Euclid's algorithm for the greatest common divisor 2.3.2 TowersOfHanoi.java devise a solution to the Towers of Hanoi problem 2.3.3 Beckett.java provide stage instructions for Beckett's play using a Gray code 2.3.4 Htree.java draw recursive graphics 2.3.5 Brownian.java draw a Brownian bridge 2.4.1 VerticalPercolation.java check whether a system vertically percolates 2.4.2 VerticalPercolation.java check whether a system vertically percolates 2.4.3 Visualize.java visualize large random percolation instances 2.4.4 Estimate.java estimate the percolation probability 2.4.5 Percolation.java check whether a system percolates 2.4.6 PercPlot.java plot percolation probability vs. site vacancy probability
Click on the program name to access the Java code; click on the reference number for a brief description; read the textbook for a full discussion.
