Search Marketing


Creating Recursion Functions for Counting

Tue Feb 02, 2010 11:00 am
<<     >>
Comments: 0 Views: 301

There are many reasons to use recursion functions. Here we are going to use such a technique to count, instead of using the traditional looping methods (for, do, do while, while).

Recursion functions are functions that at some point recall themselves. This is in effect a loop. The possible uses of such a function are creating categorizational structures, mathematics or just simple loops.

1. Create a recursion function to count from 1 to 10.

function recursive($start,$end)
echo "$start ";
if($start < $end){$x = recursive($start+1,$end);}

echo recursive(1,10);

produces: 1 2 3 4 5 6 7 8 9 10

In the above function we require two variables, the number to start from and the number to end on. This is a simple linear function. If you wanted to utilize other functions in mathematics you could just adjust the function.

2. Create a recursive function to count from 1 to 5 and take each number up to the third power.

function recursive($start,$end)
$a = pow($start,3);
echo "$a ";
if($start < $end){$x = recursive($start+1,$end);}

echo recursive(1,5);

produces: 1 8 27 64 125

pow() is a built-in PHP function and requires two variables. The first number is the number you want to start with and the second is by what power to increase it.

URL: http: (ex.
Math (26 + 4)
* required
Regular Expressions

© 2019 Christonium LLC
Terms of Use