Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 361
  • Last Modified:

Difference between recursion and iteration - JavaScript

Hi,

Can you please provide me a simple example on:

Difference between recursion and iteration - JavaScript

Thanks
0
milani_lucie
Asked:
milani_lucie
4 Solutions
 
Gurvinder Pal SinghCommented:
0
 
leakim971PluritechnicianCommented:
Test page (recursion) : http://jsfiddle.net/Mjzkk/
function factorial_recursion(n) {
      if(n!=1) n * factorial_recursion;
}

Open in new window


test page (iteration) : http://jsfiddle.net/Kvmrc/
function factorial_iteration(n) {
    a = n;
    while(n!=1) {
        n = n -1;
        a *= n;
    }
    return a;
}

Open in new window


http://en.wikipedia.org/wiki/Factorial
0
 
leakim971PluritechnicianCommented:
correction (recursion) :
function factorial_recursion(n) {
    if(n!=1) n = n * factorial_recursion(n-1);
    return n;
}

Open in new window

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
leakim971PluritechnicianCommented:
to be mathematicaly correct (and not just for the example) : 0! = 1
so :

function factorial_recursion(n) {
      if(n==0) return 1;
      if(n!=1) n * factorial_recursion(n-1);
      return n;
}

Open in new window

and :
function factorial_iteration(n) {
    if(n==0) return 1;
    a = n;
    while(n!=1) {
        n = n -1;
        a *= n;
    }
    return a;
}

Open in new window

0
 
sonawanekiranCommented:
Recursion repeatedly invokes the mechanism itself as explained by @leakim971 using factorial number. Both iteration and recursion are based on a control structure. Iteration explicitly uses a repetition structure; recursion achieves repetition through repeated method calls.

Keep in Mind:

Recursion consequently the overhead of method calls. This can be expensive in both processor time and memory space.
0
 
user_nCommented:
Recursion invokes the function itself. If you do not stop the process right it might proceed forever. It takes more space in the stack of the computer (http://en.wikipedia.org/wiki/Call_stack), because of witch it usually takes more time and memory.But in some cases it is the easiest way of finding of programing solution to a problem. Some more info (http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-algorithms-sma-5503-fall-2005/video-lectures/)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now