Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.

  • C Arithmetic Operators
  • C Variables and Constants
  • C Flow Control Structures
  • C Functions

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.

\begin{aligned}
& f_{n} = f_{n-1} + f_{n-2}
\end{aligned}

The first few terms of the series are as follows

\begin{aligned}
&0, 1, 1, 2, 3, 5, 8, 13, 21, 34, \cdots
\end{aligned}

Flowchart – Program for Fibonacci Series

Flowchart – Fibonacci Series

Program Code – Fibonacci Series

/* Program to calculate Fibonacci Series */
#include 
#include 
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
-------------------------------------------------------
Previous
Next

The post C Program To Compute Nth Fibonacci Number appeared first on Notesformsc.



This post first appeared on Notesformsc, please read the originial post: here

Share the post

C Program To Compute Nth Fibonacci Number

×

Subscribe to Notesformsc

Get updates delivered right to your inbox!

Thank you for your subscription

×