Program to print Fibonacci series

Program to print Fibonacci series

Consider the following example in which we have printed Fibonacci series using “while” loop:

CODE:

# include <stdio. h>

# include <conio. h>

void fib (int n);

void main ()

{

int n = 0;

clrscr ();

printf (“Enter a number\t”);

scanf (“%d”, &num);

fib (n);

getch ();

}

void fib (int n)

{

int x, y, z, j;

x = 0;

y = 1;

j = 1;

printf (“%d %d”,  x, y);

while (j < = num)

{

z = x + y;

x = y;

y = z;

printf (“%d”, y);

j ++;

}

}

OUTPUT:

Enter a number 5

0 1 1 2 3 5 8

Program to print fibonacci series using recursion:

Consider the following example to print fibonacci series using recursion:

CODE:

# include <stdio. h>

# include <conio. h>

void fib (int num);

void main ()

{

int n;

int x= 0, y = 1;

printf (“Enter a number “);

scanf (“%d”, &n);

printf (“Fibonacci Series: “);

printf (“%d %d “, x, y);

fibonacci (num);

getch ();

}

void fib (int num){

static long int one = 0, two = 1, sum1;

if (num > 0)

{

sum1 = one + two;

one = two;

two = sum1;

printf (“%ld “, sum1);

fib (num-1);

}

}

OUTPUT:

Enter a number 5

0 1 1 2 3 5 8