Sunday 30 June 2013

Write a program using a recursive function & LOOP to find the nth Fibonacci number.

01.

#include<stdio.h>
#include<conio.h>
int fibo(int n)
{
if(n==1||n==0)
return n;
else
return(fibo(n-1)+fibo(n-2));
}
int main()
{
int n,i;
puts("enter any number:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("%d\t",fibo(i));
}
}



02.

#include<stdio.h>
#include<conio.h>
int Fib(int x, int range);

int main(){
int r;
printf("Enter the MAx range for Fibonacci Series:\n");
scanf("%d", &r);
Fib(r,r);
printf("\n");
}
Fib(int x, int range )
{
static int sum=0,pre=0,p=1;
if (sum>=range)
return 0;
else
{
if (pre==0 && p==1 && sum==0)
{sum=pre+p;
printf("%d %d %d", pre,p,sum);
}
else
{ pre=p;
p=sum;
sum=pre+p;
printf(" %d ", sum);
}
}
Fib(sum,range);
}






Using LOOP

#include<stdio.h>
#include<conio.h>

main()
{
   int n, first = 0, second = 1, next, c;
   printf("Enter the number of terms\n");
   scanf("%d",&n);

   printf("First %d terms of fibonacci series are :\n",n);

   for ( c = 0 ; c < n ; c++ )
   {
      if ( c <= 1 )
         next = c;
      else
      {
         next = first + second;
         first = second;
         second = next;
      }
      printf("%d\n",next);
   }

   getch();
   return 0;
   }

No comments:

Post a Comment