Web Analytics Made Easy -
StatCounter Help understanding this function! - CodingForum

Announcement

Collapse
No announcement yet.

Help understanding this function!

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Help understanding this function!

    I put this function in firebug and it returns the value 24. I just need help of someone explaning me as simple but descriptive as possible how the code works.

    Code:
    function factorial(n) {
    var product= 1;
    while(n > 1) {product *= n;
    n--;
    }
    return product;
    }
    factorial(4)
    i was just reading a book and these were just one of the examples of functions which I was trying to understand better.

  • #2
    function factorial(n) { // the value of n (here 4) is passed to the function
    var product = 1; // initialise the variable product to 1
    while (n > 1) { // loop repeatedly while the value of n is a number greater than 1 (the initial value is 4)
    alert (product + " " + n); // to observe the detail of the operation
    product *= n; // multiply the current value of product by the current value of n (a shorthand for product = product * n)
    // first pass 1 * 4 = 4
    // second pass 4 * 3 = 12
    // third pass 12 * 2 = 24
    // fourth pass - n is now 1 so while loop terminates (no need to multiply by 1)
    alert (product); // to observe intermediate result
    n--; // subtract 1 from the value of n (same as n = n-1)
    } // do the while loop again as long as n is greater than 1

    alert (product); // final result 24 = 4*3*2*1 (or 4! in maths notation)
    return product; // return the value of product to the calling function
    }

    factorial(4); // call the function passing the value 4 to it


    OK?
    Last edited by Philip M; Aug 20, 2011, 04:59 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

    Comment


    • #3
      Thank you my friend! Your comments really helped.

      Comment

      Working...
      X
      😀
      🥰
      🤢
      😎
      😡
      👍
      👎