Article 130 - Recursion vs Iteration

Almost all modern programming languages define the use of recursion and iteration as looping structures.

Defintion

Recursion is, in simple words, a form of iteration but implicitly handled by the compiler.
Iteration, on the other hand, requires the programmer to explicitly declare all variables that will be needed in the looping structure.

Purpose

Consider a fragment of code that uses iteration. The programmer needs to declare the counter variable, and needs to track the base cases in the iteration. With recursion, the programmer can call the recursive function with a subset of the problem and let the program do the rest of the work.

Recursion is often easier to understand because a recursive solution is more natural and more aligned with how we think. Afterall, recursion takes a problem and recursively divides the problem into smaller problems; typically, the method in which humans solve problems.

Examples

The following is an example of recursive function.

int recursion( int count, int sum ){
    if( count <= 0 ){
        return sum;
    }

    return recursion( --count, sum + 1 );
}

The following is an example of iteration.

int iteration( int count ){
    int sum = 0;

    for( ; count > 0; count-- ){
        sum++;
    }

    return sum;
}

Comments (0)

Post a comment

  • Name:
  • Post:
  • Challenge:

Register or login to post comments easier.


Vantasy World Copyright 2011 - 2017. Vantasy World is a project developed by Vantasy Online. Privacy Policy.