#include <iostream.h> void count(int n) { std::cout << "Counting: " << n << "\n"; if (n < 5) { count(n+1); } } int main(int argc, char **argv) { count(1); return 0; }Run this example from codepad:
http://codepad.org/YmxQcTIX
In functional programming, recursion has a much more central position. Purely functional languages do not define any looping constructs, but instead rely entirely on recursion to achieve iterative algorithms. Many data types are defined recursively. In Haskell, recursion even allows us to define (conceptually) infinite data structures:
n = 5 : n take 3 n -- [5, 5, 5]Codepad: http://codepad.org/sRbFkSH5
Here, we take the first three elements from an infinite list of fives. The list n is defined as a single element, 5, followed by a list – itself.
n is a 5, followed by n, which is a 5 followed by n, which is a 5 followed …