Fibonacci numbers (C)

From LiteratePrograms
Jump to: navigation, search
Other implementations: bc | C | C Plus Plus templates | dc | E | Erlang | Forth | FORTRAN | Haskell | Icon | Java | JavaScript | Lisp | Lua | occam | Oz | PIR | Prolog | Python | Sed | sh | sh, iterative | T-SQL | Visual Basic .NET

The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by


 F(n) =
 \begin{cases}
   0             & n = 0 \\
   1             & n = 1 \\
   F(n-1)+F(n-2) & n > 1 \\
  \end{cases} .

Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist.


[edit] Implementation

The [fibonacci] numbers in C:

<<fib.c>>=
includes
fib
main
<<includes>>=
#include<stdio.h>
<<fib>>=
unsigned int fib(unsigned int n)
{
	return n<2?n:fib(n-1)+fib(n-2);
}
<<main>>=
int main()
{
	unsigned int n;
	for(n=0; n<10; ++n) printf("fib(%d)=%d\n", n, fib(n));
	return 0;
}
Download code
hijacker
hijacker
hijacker
hijacker