Deva Point

# Fibonacci Series in C

## Fibonacci Series in c

The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1 .Or you can say Fibonacci series is a series of numbers formed by the addition of the preceding two numbers in the series. The first two numbers will add to create next series number and so on.

F0 & F1. The initial values of F0 & F1 can be taken 0, 1 or 1, 1 respectively.

Fibonacci series satisfies the following conditions −

Algorithms

Fn = Fn-1 + Fn-2+Fn-3+Fn-4……

Here two ways to write the fibonacci series:

1. Fibonacci Series without recursion
2. Fibonacci Series using recursion

Program prompts user for the number of terms and displays the series having the same number of terms.

### Fibonacci Series(using for) without Recursion

Program-1

#include <stdio.h>

int main() {

int i, n;

int x1 = 0, x2 = 1;

int nextTerm = x1 + x2;

printf(“Enter the number of terms: “);

scanf(“%d”, &n);

printf(“Fibonacci Series: %d, %d, “, x1, x2);

for (i = 3; i <= n; ++i)

{

printf(“%d, “, nextTerm);

x1 = x2;

x2 = nextTerm;

nextTerm = x1 + x2;

}

return 0;

}

Output

Enter the number of terms: 12

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89

### Fibonacci Series using while function

Program-2

#include <stdio.h>

int main()

{

int a = 0, b = 1, sum = 0, n;

printf(“Enter the end term for the series: “);

scanf(“%d”, &n);

printf(“Fibonacci Series: %d, %d, “, a,b);

sum = a+b;

while(sum <= n)

{

printf(“%d, “,sum);

a = b;

b = sum;

sum = a + b;

}

return 0;

}

Output:

Enter the number of terms: 11

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55

### Fibonacci Series using Recursion Function

program to print Fibonacci series by using recursion function. Recursion is the process of repeating a funtion in a self-similar way. In c programming languages, if a program allows you to call a function itself inside the same function this process is call recursion.

Program-3

#include<stdio.h>

int fib(int t)

{

if (t <= 1)

return t;

return fib(t-1) + fib(t-2);

}

int main ()

{

int t = 8;

printf(“%d”, fib(t));

getchar();

return 0;

}

Output

21