what is the difference between recursion and iteration?

Recommended Answers

All 8 Replies

Iteration is (in essence) just looping.
Recursion is something going back into or calling itself.

Recursion can cause Iteration.

[Recursion vs. Iteration]
http://en.wikipedia.org/wiki/Recursion_(computer_science)#Recursion_versus_iteration

Iteration is like a while or for loop

for (int i = 0; i < 100; i++)

and recursion is a function calling itself for example:

using namespace std;

int function(int a) {
if (a == 100) {
cout << "\n\n\nResult reached! A = " << a;
return a;
}
else {
a++;
cout << "\nA is " << a;
return function(a);
}
}


int main() {
int i = 3;
cout << "A is " << i; //xD A is i
function(i);
return 0;
}

And I again forgot this is a C forum not C++ ! :( Use printf() instead of cout << (sorry!!)

recursion is calling a function itself..
and iteration is repeating a set of statements(block).

iteration is repeating a set of statements(block)

recursion is calling a function itself and in a function we have set of statements. does this means it is iteration??

recursion is calling a function itself and in a function we have set of statements. does this means it is iteration??

Do you think it's a basic question now? Muahahahaha!!! :D

Let's make it simple: Iteration is an explicit loop using one of C's loop constructs (for, while, do..while[1]). Recursion is an implicit loop achieved by nested calls to the same function[1].


[1] goto may be used to simulate these or other styles of explicit loop.
[2] Recursion may be direct (function A calls itself) or indirect (Function A calls function B which calls function A).

From http://www.techterms.com/definition/iteration

Iteration is the repetition of a function or process in a computer program. Iterations of functions are common in computer programming, since they allow multiple blocks of data to be processed in sequence. This is typically done using a "while loop" or "for loop" (see the examples below). These loops will repeat a process until a certain number or case is reached. Recursive functions also use iteration, though instead of repeating a process, the entire function repeats itself.

Also notice important point of tail recursion elimination and accumulator pattern to understand how all iteration can be expressed by recursion (especially Lisp/Scheme and other functional programming languages and also in Prolog)

recursion is calling a function itself and in a function we have set of statements. does this means it is iteration??

not exactly..
using some iterative statements without a call to the same function in which the control is, can be called as iteration..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.