function pickFromList returns int
{
output: Pick a number from 1 to 10
get input
if number is from 1 to 10
{
return number
}
else
{
output: Your number is not from 1 to 10
return pickFromList
}
}
Can any function that calls itself be considered recursive?
Started by Bob93, Aug 30 2010 02:31 PM
8 replies to this topic
#1
Posted 30 August 2010 - 02:31 PM
For instance this: (pseudocode)
|
|
|
#2
Posted 30 August 2010 - 05:05 PM
It can be, but I would consider that function a great example of when NOT to use it.
#3
Posted 30 August 2010 - 09:37 PM
Why is it a bad idea to use it like this?
Should I use a while loop instead?
Thanks.
Should I use a while loop instead?
Thanks.
#4
Posted 31 August 2010 - 01:38 AM
Normally, a recursive function should have a control variable to avoid an infinite loop. In your case, i think you should specify the size of the list and the logic in which you are picking your numbers.
becuase the way it is, it is very possible to run into an infinite loop.
Good Luck!
becuase the way it is, it is very possible to run into an infinite loop.
Good Luck!
#5
Posted 31 August 2010 - 04:25 AM
It's a bad idea because when you call the method, the system has to add more information to the stack (yes, I see you Functional languages with your tail recursive optimization, but this is true most of the time!) and eventually you'll run out of stack space and your program will crash. A while loop is a much better choice.
#6
Posted 31 August 2010 - 09:28 PM
Thanks for the replies
Would using a while(true) loop be a good idea?
Would using a while(true) loop be a good idea?
function pickFromList returns int
{
while (true)
{
output: Pick a number from 1 to 10
get input
if number is from 1 to 10
{
return number
}
else
{
output: Your number is not from 1 to 10
}
}
}
#7
Posted 31 August 2010 - 10:26 PM
Yes, using a while loop would be a good idea :)
#8
Posted 01 September 2010 - 12:54 AM
Bob93 said:
Why is it a bad idea to use it like this?
Should I use a while loop instead?
Thanks.
Should I use a while loop instead?
Thanks.
Recursive call is much more expensive than iteration because complete stack frame must be built, containing all arguments to the method, some register values, local variables, return address... This is not a small structure anyway, and that's why recursive call is slow compared to iteration.
#9
Posted 01 September 2010 - 04:28 AM
Bob93 said:
Thanks for the replies
Would using a while(true) loop be a good idea?
Would using a while(true) loop be a good idea?
function pickFromList returns int
{
while (true)
{
output: Pick a number from 1 to 10
get input
if number is from 1 to 10
{
return number
}
else
{
output: Your number is not from 1 to 10
}
}
}

Sign In
Create Account

Back to top









