Home » C Examples » C Program To Compute Nth Fibonacci Number

C Program To Compute Nth Fibonacci Number

The program computes Nth Fibonacci number using a technique called recursion and prints the results. A recursion is the ability of a procedure or function to call itself several times.

You can write the program without recursion, but computer science students learn Fibonacci series as an introduction to recursion or recurrence relations. It is a topic of higher importance in both mathematics and computer science.

We compiled the program using Dev-C++ version 4 compiler on a Windows 7 64-bit system, but you can also compile the program using another standard C compiler such as Turbo C++ 3 with modified source code. The choice of compiler is up to the programmer.

You should learn the following C programming concepts before trying the example program.

Problem Definition

In mathematics, the whole number means all positive numbers starting with 0. Any term in Fibonacci series takes a sum of previous two terms. The formula for the nth term of Fibonacci series is given below.

``$f_{n} = f_{n-1} + f_{n-2}$``

The first few terms of the series are as follows

`` 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... ``

Program Code – Fibonacci Series

``````/* Program to calculate Fibonacci Series */
#include < stdio.h >
#include < stdlib.h >
main ()
{
int n;
void fib ();
printf ("Number of terms to be generated?");
scanf ("%d", & n);
printf ("%d", n);
printf ("\n\n Fibonacci sequence up to %d terms :\n\n");
fib(n);
printf("\n");
system("PAUSE");
return 0;
}

void fib(int n)
{
static long int f1 = 0, f2 = 1, sum;
if (n > 0)
{
sum = f1 + f2;
f1 = f2;
printf("%5d", sum);
f2 = sum;
fib(n - 1);
}
}``````

Output

``````Number of terms to be generated?:8
Fibnacci sequence upto 8 terms :
-------------------------------------------------------
1     2     3     5     8     13    21     34
-------------------------------------------------------``````