Saturday, December 10, 2011

Recursion function in JavaScript

Recursion is an important programming technique. It is used to have a function call itself from within itself. One example is the calculation of factorials. The factorial of 0 is defined specifically to be 1. The factorials of larger numbers are calculated by multiplying 1 * 2 * ..., incrementing by 1 until you reach the number for which you are calculating the factorial.
Here is the factorial function again, this time written in JavaScript code with asp.net. If the number is less than zero, reject it. If it is not an integer, round it down to the next integer. If the number is zero, its factorial is one. If the number is larger than zero, multiply it by the factorial of the next lesser number.

Here is javascript.
<script type="text/javascript">
function factorial(aNumber)
{
    // If the number is not an integer, round it down.
    aNumber = Math.floor(aNumber);
    // If the number is less than 0, reject it.
    // If the number is 0, its factorial is 1.
    // Otherwise, call this recursive procedure again.
    if (aNumber < 0)
    {
       return -1;
    }
    else if (aNumber == 0)
    {
      return 1;
    }
    else
    {
      return (aNumber * factorial(aNumber - 1));
    }
}
function Calculate()
{
    var num = $get('<%=txtNum.ClientID%>');
    var dis = $get('lblDisplay');
    dis.innerText = factorial(num.value);
}
</script>

 
Form tag go here.
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <asp:Button ID="btnCal" runat="server" Text="Calculates a factorial" OnClientClick="javascript:Calculate();return false;"/>
        <asp:TextBox ID="txtNum" runat="server"></asp:TextBox>
        <asp:Label ID="lblDisplay" runat="server" Text=""></asp:Label>
    </div>
</form>

I use here ASP.NET AJAX $get method to get the value of textbox and it is safe to use asp.netcontrol.ClientID for asp.net server control. I have to put ScriptManager since I used $get method. Moreover, make sure that it use innerText property for Label. Thank.

Note : it is also important for some interview (due to my experience) :P

No comments:

Post a Comment