/**************************************************** * A program to compute and print Fibonacci numbers * * using recursion and iteration. * ****************************************************/ #include /* Function prototypes */ void recfib(int,int,int,int); void iterfib(int); int main() { int fnum = -1; /* Read in a value until a valid one is provided */ do { printf("Please enter the number of Fibonacci"); printf(" numbers you would like to see: "); scanf("%d", &fnum); } while(fnum < 1); printf("Printing %d Fibonacci numbers recursively\n", fnum); /* Print the Fibonacci numbers using recursion. */ recfib(fnum,0,1,0); printf("Printing %d Fibonacci numbers iteratively\n", fnum); /* Print the Fibonacci numbers iteratively. */ iterfib(fnum); return 0; } /* function recfib * * This function prints Fibonacci numbers recursivly. * * parameters: * * n - the number of Fibonacci numbers left to print * * f_1 - the current Fibonacci number * * f_2 - the next Fibonacci number * * k - the current position in the list of Fibonacci * * numbers */ void recfib(int n, int f_1, int f_2, int k) { /* If we are on the last Fibonacci number, print it and return */ if(n == 0) { printf("%5d: %5d\n",k,f_1); } /* Otherwise print the current Fibonacci number and call recfib * again to print the next number */ else { printf("%5d: %5d\n",k,f_1); recfib(n-1, f_2, f_2+f_1, k+1); } } /* function iterfib * * This function prints Fibonacci numbers iteratively * * parameters: * * fnum - the number of Fibonacci numbers to print */ void iterfib(int fnum) { /* Declare variables */ int i = 0, current = 1, current_1 = 0, temp; /* Begin the loop to print out the Fibonacci numbers */ for(i = 0; i <= fnum; i++) { /* If printing out f_0 or f_1, just print them */ if(i == 0) printf("%5d: %5d\n", i, 0); else if(i == 1) printf("%5d: %5d\n", i, 1); /* otherwise, compute the current Fibonacci number using * the previous two Fibonacci numbers */ else { temp = current; current = current + current_1; current_1 = temp; printf("%5d: %5d\n", i, current); } } }