4/4/08

Fibonacci in C

This code calculates the Fibonacci of a number inputted by user. Calculation is done with recursion and not.
Fibonacci is declared as followed:

fibonacci(n) = fibonacci(n-1) + fibonacci(n-2) n>=2
fibonacci(0) = 0
fibonacci(1) = 1

Here is the source code of Fibonacci in C:

#include <stdio.h>

int fibonacci(int y){
if (y==0) return 0;
if (y==1) return 1;
return( fibonacci(y-1)+fibonacci(y-2) );
}

int fibonacci2(int a) {
if (a==0) return 0;
if (a==1) return 1;

int x,y,z,i;
for (i=1,x=0,y=0,z=1;i<a;i++) {
x=y+z;
y=z;
z=x;
}
return(x);
}
int main() {
int x;
printf("Give an integer ");
scanf("%d",&x);
printf("Fibonacci of %d is %d ",x,fibonacci(x));
printf("\nFibonacci2 of %d is %d ",x,fibonacci2(x));
exit (0);
}

Example of output:

Give an integer: 30
Fibonacci of 30 is 832040
Fibonacci2 of 30 is 832040

No comments: