Can some explain the difference between the two?
:)
Printable View
Can some explain the difference between the two?
:)
Recursion: a function calling itself
Iteration: a loop such as For, While, etc.
They're two completely different things. Recrusion is when a function calls itself, and iteration is one repetition of a sequence of instructions/events (e.g. in a loop, one iteration is once through the code in the loop)
Thanks
:)
Examples:Quote:
Originally posted by filburt1
Recursion: a function calling itself
Iteration: a loop such as For, While, etc.
Both return (except for the billions of bugs I didn't notice :)) the sum from 0 to x.Code:// recursion:
int stuff(int x)
{
if (x == 0) return 0;
else return stuff(x - 1);
}
// iteration
int someValue = 0;
for (int i = 0; i < x, i++)
{
someValue += i
}
The recursion example looks like it returns 0 =).
Z.Code:stuff(4) returns 0
return (4-1) returns 0 ^
return (3-1) returns 0 ^
return (2-1) returns 0 ^
return (1-1) -> returns 0 ^
[edit]
It does, the code should look like:
Code:int stuff(int x) {
if(x == 0) return 0;
else return x + stuff(x-1);
}
Heh, I told you there'd be bugs. ;) But the basic concept is there. :)
Quite =).
Z.