+ 1
Loops and recursion
what are the differences between loops and recursion. (I'm soo confuse) examples are optional but would be nice.
5 Respuestas
+ 14
Loops enable a certain part of the code to be executed several times until a certain condition is satisfied and the recursion is a phenomenon that the function invokes itself until a certain condition is satisfied or not.
+ 13
Here is example for factorial:
Loop:
while(number >= 2)
{
factorial *= number--;
}
Recursion:
static int Factorial(int x)
{
if(x == 1)
return 1;
else
return x * Factorial(--x);
}
+ 2
Loops are a straight forward method of making a piece of code run a specific amount of times, or until a certain condition is met. They are built in to a programming language.
Recursion is more like a technique or phenomenon. It's made possible by the fact that a function can call itself as it's argument.
So take the following function (I'ma use some generic made-up syntax, since I haven't messed with Java in a while):
func myFunc(int x)
{
if (x == 0)
{
return x;
}
else
{
myFunc(--x);
}
}
So, assuming we input a positive integer for the above function's parameter, if the integer we put in is equal to 0, we'll return 0. Otherwise, we'll call myFunc again, but with the parameter lowered by one. Eventually, x will == 0, and the function's code will end.
One popular intro to recursion is finding the factorial of a number. I would Google to find other simple uses for recursion to begin.
+ 2
While, Do-while, and For loops are all types of loops.
If and Switch statments only check to see if a condition is true and will run a specific piece of code depending on whether that condition is true or not. They are NOT loops. However, you can use them in loops, and you can use loops in If and Switch statements. Depends on what you need.
You can make any function you create recursive. It's up to you to decide whether or not you need to.
+ 1
while statements are recursions and if and for statements are loops?