The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. 
Home Fruitful Methods One More Example  
Search the VIAS Library  Index  
One More Example
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: if (n == 0) { return 1; } else { return n * factorial (n1); } } 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 factorial, the classic example of a recursivelydefined mathematical function is fibonacci, which has the following definition:
Translated into Java, this is public static int fibonacci (int n) {if (n == 0  n == 1) { return 1; } else { return fibonacci (n1) + fibonacci (n2); } } If you try to follow the flow of execution here, even for fairly small values of 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.


Home Fruitful Methods One More Example 