[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Difference between for and while loop



Richard Hector wrote:

> On Fri, Apr 18, 2003 at 04:40:00PM +0300, Aryan Ameri wrote:
> > On Friday 18 April 2003 13:46, Frank Gevaerts wrote:
> 
> > > - theoretical : both while and for loops are unneeded : recursion is
> > >   much nicer
> > 
> > Newbish question, what's recursion ?
> 
> Calling a function from within itself - this example calls itself directly,
> but it could call a second function which calls the first or whatever.
> 
> This is the classic example, though I'm not guaranteeing it's correct :-)
> 
> int factorial(int n){
>   if (n == 0)
>     return 0;
>   if (n == 1)
>     return 1;
>   else
>     return (n * factorial(n-1));
> }
> 
> If used inappropriately it can chew up all your memory.

Or overflow your stack, at least. In some languages, where function call
return data is dynamically allocated rather than stored in a static
array, it actually can use up all available memory, but C is not one of
those languages.

> Failing to have a
> condition under which it terminates is a disaster (like if you call the
> above with a negative number ...).

So change n == 0 to n <= 0 above. Since factorial is undefined for
negative numbers, it's a reasonable answer, and it avoids the infinite
recursion problem.

> I saw a classmate several years ago code his main event loop by recursing
> main() - it ran out of memory very quickly :-)

You can (and often should) do that in languages that support tail
recursion optimization (Scheme, Erlang, ...), but C is not one of those
languages.

Craig

Attachment: pgpS08udATPta.pgp
Description: PGP signature


Reply to: