Next: , Up: The First Example   [Contents][Index]


1.1 Example: Recursive Fibonacci

To introduce the most basic features of C, let’s look at code for a simple mathematical function that does calculations on integers. This function calculates the nth number in the Fibonacci series, in which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ….

int
fib (int n)
{
  if (n <= 2)  /* This avoids infinite recursion.  */
    return 1;
  else
    return fib (n - 1) + fib (n - 2);
}

This very simple program illustrates several features of C:


Next: , Up: The First Example   [Contents][Index]