/*
Source: fib.c
Author: Yana
What:
-----
This program computes the n'th Fibonacci number.
Input: A non-negative valid integer n.
Output: The n'th Fibonacci number.
How:
----
Algorithm: Uses iterative fibonacci(int n) function.
*/
#include<stdio.h >
/* Function protoype. */
int fibonacci(int n);
int main(){
- int num; /* Input number. */
- printf("Please Enter an integer: ");
- scanf("%d", &num);
- printf("The %d Fibonacci number is: %d\n ", num, fibonacci(num));
- return 0;
}
/* fibonacci: Finds n'th Fibonacci number.
Parameters: n (input parameter).
Returns: n'th Fibonacci number.
Algorithm: Iterative, using the formula f(n) = f(n - 1) + f(n - 2),
n >= 2
f(0) = f(1) = 1 */
int fibonacci(int n){
- int f_prev = 1; /* f( n - 1 ) (initialized to f(1) = 1) */
- int f_prev_prev = 1; /* f( n - 2 ) (initialized to f(0) = 1) */
- int f_current; /* f( n ) */
- int counter; // counts number of iterations.
- if ( n <= 1 ){
- }
- else{
- for (counter = 2; counter <= n; counter ++){
- f_current = f_prev + f_prev_prev;
- f_prev_prev = f_prev;
- f_prev = f_current;
- }
- }
- return (f_current);
}