Chapter 6 Methods 219 Common Programming Error 6.15 (Web host 4 life)

Chapter 6 Methods 219 Common Programming Error 6.15 Omitting the base case or writing the recursion step so that it does not converge on the base case will cause infinite recursion, eventually exhausting memory. Infinite recursion is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution. 6.15 Example Using Recursion: The Fibonacci Series The Fibonacci series 0,1, 1, 2, 3, 5, 8, 13, 21, begins with 0 and 1 and has the property that each subsequent Fibonacci number is the sum of the previous two Fibonacci numbers. The series occurs in nature and, in particular, describes a form of spiral. The ratio of successive Fibonacci numbers converges on a constant value of 1.618 . This number, too, repeatedly occurs in nature and has been called the golden ratio or the golden mean. Humans tend to find the golden mean aesthetically pleasing. Architects often design windows, rooms and buildings whose length and width are in the ratio of the golden mean. Postcards often are designed with a golden mean width-to-height ratio. The recursive definition of the Fibonacci series is as follows: Fibonacci( 0 ) = 0 Fibonacci( 1 ) = 1 Fibonacci( n ) = Fibonacci( n 1 ) + Fibonacci( n 2 ) Note that there are two base cases for the Fibonacci calculation fibonacci(0) evaluates to 0, and fibonacci(1) evaluates to 1. The application in Fig. 6.16 calculates the ith Fibonacci number recursively using method Fibonacci. The user enters an integer in the text box, indicating the ith Fibonacci number to calculate, and clicks the calculateButton (which displays the text Calculate Fibonacci). Method calculateButton_Click (lines 22 29) executes in response to the user interface event and calls recursive method Fibonacci to calculate the specified Fibonacci number. In Fig. 6.16, the screen captures show the results of calculating several Fibonacci numbers. 1 // Fig. 6.16: FibonacciTest.cs 2 // Recursive fibonacci method. 3 using System; 4 using System.Drawing; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Windows.Forms; 8 using System.Data; 9 10 public class FibonacciTest : System.Windows.Forms.Form 11 { 12 private System.Windows.Forms.Button calculateButton; 13 14 private System.Windows.Forms.TextBox inputTextBox; Fig. 6.16 Recursively generating Fibonacci numbers. (Part 1 of 2.)
You need excellent and relaible webhost company to host your web applications? Then pay a visit to Inexpensive Web Hosting services.

Leave a Reply