Thursday, 1 June 2017

Fibonacci Series in C ~ GNIITHELP

Program to print Fibonacci Series

Following is the program to print Fibonacci series using while loop.
#include<stdio.h>
#include<conio.h>
void fibonacci(int num);

void main()
{
   int num = 0;
   clrscr();
   printf("Enter a number\t");
   scanf("%d", &num);
   fibonacci(num);
   getch();
}

void fibonacci(int num)
{
   int a, b, c, i;
   a = 0;
   b = 1;
   i = 1;
   printf("%d\t%d", a, b);
   while(i <= num)
   {
      c = a+b;
      a = b;
      b = c;
      printf("\t%d", b);
      i++;
   }
}
Output
Enter a number 5
0  1 1 2 3 5 8 

Program to print Fibonacci Series using Recursion

Now lets print the fibonacci series using recursion.
#include<stdio.h>
#include<conio.h>

void fibonacci(int num);

void main()
{
    int n;
    int i = 0, j = 1;
    printf("Enter the range of the Fibonacci series: ");
    scanf("%d", &n);
    printf("Fibonacci Series: ");
    printf("%d %d ", i, j);
    fibonacci(n);
    getch();
}

void fibonacci(int n){
    static long int first = 0, second = 1, sum;
    if(n > 0)
    {
         sum = first + second;
         first = second;
         second = sum;
         printf("%ld ", sum);
         fibonacci(n-1);
    }
}
Output
Enter the range of the Fibonacci series: 5
Fibonacci Series: 0 1 1 2 3 5 8

No comments:

Post a Comment