Friday, January 1, 2016

C programs related to Fibonacci series

C program to find Fibonacci series without recursion
#include <stdio.h>
int main(void) {
  int n = 10; // print n fibonacci series
  int a = 0, b = 1, s;
  printf("%d %d ", a,b);
  n = n - 2; // already 2 numbers printed
  while(n--){
  s = a + b;
  printf("%d ",a+b);
  a = b;
  b = s;
  }
  return 0;
}


C program to find Fibonacci series with recursion
#include <stdio.h>
int fibo(int);
int main(void) {
  for(int i = 0; i < 5; i++)
    printf("%d ",fibo(i));
  return 0;
}

int fibo(int n){
  if(n > 1){
    return fibo(n-1) + fibo(n-2);
  }
  else{
    return n;
  }
}

C program to find nth Fibonacci number
#include <stdio.h>
int fibo(int);
int main(void) {
  int position = 5;
  printf("The fibonacci number at position %d is %d ",position,fibo(position-1));
  return 0;
}

int fibo(int n){
  if(n > 1){
    return fibo(n-1) + fibo(n-2);
  }
  else{
    return n;
  }
}

No comments:

Post a Comment