[prog] functions
cristofd at hevanet.com
cristofd at hevanet.com
Mon Jan 12 11:17:23 EST 2004
> What is the
> difference between recursion and iteration
> and why would you chose to use one over the other?
Iteration involves an explicit command to perform some set of actions
repeatedly until some condition holds; in C++ this is typically done
with a while loop or a for loop.
Recursion involves a function which performs some set of actions and
also calls itself (directly or indirectly) unless some condition holds;
in C++ the self-call is put directly into the function definition.
Quick example: find factorial of n (that is, 1*2*3*4*...*n)
With iteration:
fac = 1;
for (i=1;i<=n;i++){
fac = fac * i;
}
With recursion:
int fac(int n){
if (n==0){
return 1;
}else{
return n*fac(n-1); /*here fac calls itself but with a different
argument*/
}
}
Anything that can be done with iteration can be done with recursion, and
vice versa. In fact, some whole languages only allow using one or the
other. In C++, where both are possible, the reasons to choose iteration
are A. that it will sometimes lead to clearer and more concise code, and
B. that that code may end up running faster and/or using less memory
once it's compiled. The reason to choose recursion is that IT will
sometimes lead to clearer and more concise code. Which is better really
depends on
conte
More information about the Programming
mailing list