HTML and CSS Reference
In-Depth Information
The variable, count , is initialized outside the function, making it global. It will
keep track of the number of times the fib() function is called.
The fib() function introduces the concept of recursion, a function that calls itself.
This function starts the initial task and in itself is not recursive. When the same
task needs to be repeated, that is when fib() will call itself.
Each time the function is called, the value of count is incremented by 1.
The first two Fibonacci numbers are 0 and 1, and each remaining number is the
sum of the previous two. The switch statement is used to check for the incoming
values of a number, num . If num is 0, the value returned will be 0; if it is 1, the
value returned is 0 + 1. Because these cases are so simple there is no need for re-
cursion. If the number is greater than 1, then the default case is entered.
The first values in the sequence are 0 and 1. The value 1 is returned.
This is the heart of the recursive program. If the number is not 0 or 1, the default
case is entered, and the remaining number is the sum of the previous two num-
bers. The function fib() is used within its own definition. The result of the first
call to the fib() function is added to the result of next call to fib( ) , returning the
result to line 8.
The loop iterates 20 times. For each iteration, the function fib() is called, which
calls itself.
Each time through the for loop, the function fib() is called passing the value n as
its argument (see line 6).
The value of the count variable increases by one every time the fib() function is
called. With recursion, the function was called 35,400 times (see Figure 7.15).
Figure 7.15 Recursion with the Fibonacci series.
Search WWH ::

Custom Search