printfpowf d fn x n powx n systempause return 0 double powdouble x int n if n 0

# Printfpowf d fn x n powx n systempause return 0

This preview shows page 13 - 16 out of 16 pages.

printf("pow(%f, %d) = %f\n", x, n, pow(x, n)); system("pause"); return 0; } double pow(double x, int n) { if (n == 0) return 1; /* simple case */ else return x * pow(x, n - 1); /* recursive step */ } 14 Example 4: Fibonacci Function Suppose we wish to define a function to compute the nth term of the Fibonacci sequence. Fibonacci is a sequence of number that begins with the term 0 and 1 and has the property that each succeeding term is the sum of the two preceding terms: Thus, the sequence is: 0, 1, 1,2,3,5,8,13,21,34 … Mathematically, the sequence can be defined as: fib(n-1) + fib(n-2) n>1 n, n = 0, 1 fib(n) 15 Example 4: Fibonacci Function #include <stdio.h> int fib(int n); int main(void) { int n; printf("Enter an integer n to find the nth fibonacci term: "); scanf("%d", &n); printf("fibonacci(%d) = %d\n", n, fib(n)); system("pause"); return 0; } int fib(int n) { if (n == 0 || n== 1) return n; /* simple case */ else return fib(n-1) + fib(n-2); /* recursive step */ } 16 Tracing using Recursive Tree Another way to trace a recursive function is by drawing its recursive tree. This is usually better if the recursive case involves more than one recursive calls. Rrecursive tree of the Fibonacci function #### You've reached the end of your free preview.

Want to read all 16 pages?

• • •  