Notation styles: Iterative and Recursive

There are almost countless different approaches to achieving a programming goal. In general, a distinction is made between iterative and recursive programming styles. The procedural style will not be covered, as it is less prominent in modern programming languages.

In this article, the power algorithm is taken as a basis to illustrate the difference between each style.

Iterative notation

In the iterative programming approach, a problem is divided into smaller, recurring steps that are processed in loops.

function calculatePowerOf(number, potency) {
    solution = 1;
    for (i = 0 ; i < potency ; i++) {
        solution *= number;
    }
    return solution;
}

Recursive notation

In the recursive approach, the solution to a problem is described in such a way that it contains itself as a part or is defined with the help of itself.

function calculatePowerOf(base, exponent) {
    if (exponent <= 1) {
        return base;
    }
    return calculatePowerOf(base * base, exponent - 1);
}

The advantage of this is that it shortens formulations and reduces the number of variables needed.

What speaks against it is that it takes some getting used to and in certain cases the speed of execution takes a toll due to the overhead involved.

The most important components of a recursive approach are:

  • Base case / termination condition (exponent <= 1)
  • General case (return calculatePowerOf(base * base, exponent – 1)
  • Progress (exponent – 1)

Important: Please note that every recursive function can be described iteratively and every iterative function can be described recursively.