0
Can recursion be an alternative to loops ?
13 Answers
+ 11
Yes, but generally not encouraged due to the tendency of incurring implicit bugs.
+ 8
Recursion is sometimes the easiest and code-length-wise the shortest way to achieve certain goals which involve a repeating pattern.
As the guys said, though, it is often resource-consuming (time and/or memory). Be sure that you have enough supplies :)
Also, a remark. Remember to always-always include the base condition in the recurring part of your code. Otherwise, you might end up with an infinite loop.
Take a look on one of my codes which engages recursion for generating a labyrinth:
https://code.sololearn.com/cL8CKWRqS2XN/?ref=app
+ 8
@Raihan Ahmed If you barred me from using all kinds of loops, what option do I have apart from recursion lol? That forfeits the purpose of comparing recursion to loops anyways.
+ 5
For some , sometimes (very rarely ) Recursion becomes a solution for their problem. Some recursion problems are easy to understand if you know the concept of recursion.
Example: Consider a program to find factorial of a given number. Let's say for 5. We know factorial of 5 =120.
---------------Without Recursion----------------
int fact=1;
for(int c=1; c<5; c++)
{
fact=fact*c;
}
-----------------Using Recursion-----------------
long factorial(int fact) // Assume fact=5 initially
{
if(fact==0)
return 1;
else
return fact* factorial(fact);
}
+ 3
Every problem that is solved by recursion can also be solved by ordinary iteration by loops.
Recursion also consumes more processing time due to the pushing and popping from the stack.:-)
+ 2
of course you can go for recursion.
But since you didn't mention "goto" in the list 'goto' label can be used with if condition and 'break' to get the effect of loop.
PS: goto usage in programming is not recommended.
+ 2
Are you telling goto was restricted in python..(which I don't know -still learning)
in c++ it's possible.
Was that an assignment problem??
Keep coding :-)
+ 1
Recursion can be an alternative to loops but if one is not careful with error checking a recursion function can run indefinitely until stack space has been exhausted. Looping may run forever, but will not exhaust stack memory while the loop is executing no matter how long it takes to complete its work. It may, however, exhaust heap space if each iteration creates new variables to store temporary data.
0
most common employment of recursion Aswin âș
0
Hatsy Rei if I ask u to sum up the elements of an integer array where your code can not contain any of the following words :
for
while
import
math
sum
what would u do rather using recursion ? I currently use python 3
0
Yep aswin but refer to my comment for Rei. wont it be more suitable to use recursion ?
0
just checked Aswin goto was also restricted. Otherwise I would have tried that
0
bug finded on Aswin's A factorial for loop example: "c < 5"
it must be "c <= 5"