How to find factorial of a number using C# and VB.net

Introduction: In this article i have explained how to get/find/calculate factorial of a number in asp.net.
  • In the design page(.aspx) place two text boxes and a button as:
<table>
            <tr>
                <td>
                    Enter number</td>
                <td>
                    <asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    <asp:Button ID="btnFactorial" runat="server" Text="Calculate factorial"
                        onclick="btnFactorial_Click" />
                </td>
            </tr>
            <tr>
                <td>
                    Output:</td>
                <td>
                    <asp:TextBox ID="txtFactorial" runat="server"></asp:TextBox>
                </td>
            </tr>
        </table>
  • Now in the code behind file(.aspx.cs) write the code as:

C#.Net Code to get/find/calculate factorial of a number using C# and VB.net

    protected void btnFactorial_Click(object sender, EventArgs e)
    {
        int count = 1, factorial = 1, number = 1, factorialNumber;

        factorialNumber = Convert.ToInt32(txtNumber.Text);

        while (count <= factorialNumber)
        {
            factorial = factorial * number;
            count++;
            number++;
        }

        txtFactorial.Text = factorial.ToString();
    }


VB.Net Code to get/find/calculate factorial of a number using C# and VB.net
  • Now in the code behind file(.aspx.vb) write the code as:
    Protected Sub btnFactorial_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim count As Integer = 1, factorial As Integer = 1, number As Integer = 1, factorialNumber As Integer

        factorialNumber = Convert.ToInt32(txtNumber.Text)

        While count <= factorialNumber
            factorial = factorial * number
            count += 1
            number += 1
        End While

        txtFactorial.Text = factorial.ToString()
    End Sub


Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..