Difference between recursion and iteration
Recursion and iteration are two very commonly used, powerful methods of solving complex problems, directly harnessing the power of the computer to calculate things very quickly. Both methods rely on breaking up the complex problems into smaller, simpler steps that can be solved easily, but the two methods are subtlety different.
Iteration, perhaps, is the simpler of the two. In iteration, a problem is converted into a train of steps that are finished one at a time, one after another. For instance, if you want to add up all the whole numbers less than 5, you would start with in the 1st step, then in step 2 add 2, then in step 3 add 3, and so on. In each step, you add another number which is the same number as the number of the step you are on. This is called "iterating through the problem." The only part that really changes from step to step is the number of the step, since you can figure out all the other information like the number you need to add from that step number. This is the key to iteration: using the step number to find all of your other information. The classic example of iteration in languages like BASIC/C++, of course, is the for loop. If iteration is a bunch of steps leading to a solution, recursion is like piling all of those steps on top of each other and then quashing them all into the solution. Recursion is like holding a mirror up to another mirror: in each image, there is another, smaller image that's basically the same.
Example of recursion program:
int factorial(int a)
{
if (a < 0)
{
cout << "Error, negative argument to factorial ";
exit(1);
}
else if (a == 0)
{
return 1;
}
else
{
return (a * factorial(a - 1));
}
}
Example of Iteration program:
int factorial(int number)
{
int product = 1;
if (a < 0)
{
cout << "Error, negative argument to factorial";
exit(1);
}
else if (a == 0)
{
return 1;
}
else
{
for ( ; a > 0 ; a--)
fact *= a;
return fact;
}
}
So, the difference between iteration and recursion is that with iteration, each step clearly leads onto the next, like stepping stones across a river, while in recursion, each step replicates itself at a smaller scale, so that all of them combined together eventually solve the problem. These two basic methods are very important to understand fully, since they appear in almost every computer algorithm ever made.
Thanks
Mukesh Rajput
Post A Comment:
0 comments: