Originally Posted by
Salem
Only the most perverse coder would have a recursive strlen() function for example
I guess this would include quite a few lecturers from the university I attend(word?) to Especially those with a functional language background like Scheme.
The difference between a recursive and an interative function isn't always clear. For one, a function that calls itself doesn't always have to be a recursive function. Usually a recursive algorithm doesn't produce any kind of result until the last layer of recursion is reached. Once this happens, the "real" calculations begin - backwards.
Consider f: f(x)= { 0 for x==0; f(x -1) +1 otherwise }
Code:
f(4) =>
f(3) +1 =>
(f(2) +1) +1 =>
((f(1) +1) +1) +1 =>
(((f(0) +1) +1) +1) +1 =>
0 +1 +1 +1 +1 = 4
As you can see, a real stack is built but nothing is known about the result until the bottom is hit. This is a recursive function.
This one is - strictly speaking - not recursive, although it calls itself:
Code:
int iter_main(int x) {
int iter_sub(int i, int j) {
if (j-- <= 0)
return i;
else
return iter_sub(i++, j);
}
return iter_sub(0, x);
}
I admit, it's not really apparent. It's late here and I couldn't come up with something better
(I didn't test it - hopefully there are not typos in it.)