Web hosting providers - Chapter 6 Methods 221 Fibonacci( 3 ) return

Chapter 6 Methods 221 Fibonacci( 3 ) return return + + return 1 return 1 return 0 Fibonacci( 2 ) Fibonacci( 1 ) Fibonacci( 1 ) Fibonacci( 0 ) Fig. 6.17 Set of recursive calls to method Fibonacci. This figure raises some issues about the order in which C# compilers will evaluate operands. Figure 6.17 shows that, during the evaluation of Fibonacci(3), two recursive calls will be made Fibonacci(2) and Fibonacci(1). In what order will these calls be made? Most programmers assume the operands will be evaluated from left to right; in C# this is indeed true. The C and C++ languages (on which many of C# s features are based) do not specify the order in which the operands of most operators (including +) are evaluated. Therefore, in those languages, the programmer can make no assumption about the order in which these calls execute. The calls could, in fact, execute Fibonacci(2), then Fibonacci(1), or they could execute in the reverse order (Fibonacci(1), then Fibonacci(2)). In this program and in most other programs, the final result would be the same. However, in some programs, the evaluation of an operand could have side effects that would affect the expression s final result. C# specifies that the order of evaluation of the operands is from left to right. Thus, the method calls are first Fibonacci(2), then Fibonacci(1). Good Programming Practice 6.5 Do not write expressions that depend on the order of evaluation of the operator s operands. Doing so often results in programs that are difficult to read, debug, modify and maintain. A word of caution about using a recursive program to generate Fibonacci numbers: each invocation of the Fibonacci method that does not match one of the base cases (i.e., 0 or 1) results in two recursive calls to the Fibonacci method. This quickly results in many method invocations. Calculating the Fibonacci value of 20 using the program in Fig. 6.16 requires 21,891 calls to the Fibonacci method; calculating the Fibonacci value of 30 requires 2,692,537 calls to the Fibonacci method. As the programmer tries larger values, each consecutive Fibonacci number that the program is asked to calculate results in a substantial increase in the number of calls to the Fibonaccimethod and hence in calculation time. For example, the Fibonacci value 31 requires 4,356,617 calls, and the Fibonacci value of 32 requires 7,049,155 calls. As you can
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

Leave a Reply