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!!)

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..

Edited 5 Years Ago by sharathg.satya: n/a

This article has been dead for over six months. Start a new discussion instead.