Search code examples
c#numbersfactorial

c# even number and factorial


So I have problem... I need to build program with C# windows form, and calculate with texbox1 and textbox2 factorials and show even numbers in richtextbox, and use FOR cycle, I have builded this solution but it gives me only one number.....It is mind****.... If you know what I mean... Any sugestions?

private void button1_Click(object sender, EventArgs e)
    {
        int x = Convert.ToInt32(textBox1.Text);
        int y = Convert.ToInt32(textBox2.Text);
        int fact = 1;
        for (int i = x; i<=y; i++)
        {
            fact = fact * y;
        }
        richTextBox1.Text = fact.ToString();
    }

Well In mind I have build this one too, what do you think about it? And maby someone can tell me how to use it?

for (int i = X; i <= Y; i++)
    if (i % 2 == 0)
    {
        fakt = 1;

        for (int j = i; j > 0; j--)
            fakt = fakt * j;
    }

Solution

  • Let's start by defining our factorial function. You said it had to be a for loop, so:

    private int Factorial(int n) {
        int result = 1;
        for (int i = 2; i <= n; i++)
            result *= i;
        return result;
    }
    

    Now, you said you wanted the textbox to have the format:

    X = 1; Y = 4;
    =======================|Number|Factorial|====================
    =======================|2|2|=================================
    =======================|4|24|================================
    

    Let's start by making a function that will print the column headers:

    private void PrintHeaders(int x, int y) {
        StringBuilder builder = new StringBuilder();
        builder.AppendFormat("X = {0}; Y = {1}", x, y);
        builder.AppendLine();
        builder.AppendLine("===============|Number|Factorial|=============");
        richTextBox1.Text = builder.ToString();
    }
    

    And, lastly, our click event handler:

    private void button1_Click(object sender, EventArgs e) {
        int x = Convert.ToInt32(textBox1.Text);
        int y = Convert.ToInt32(textBox2.Text);
        PrintHeaders(x, y);
        for(int i = x; i <= y; i++) {
            if(i % 2 == 0) {
               int result = Factorial(i);   
               richTextBox1.Text += "==========|" + i + "|" + result + "|=============";
               richTextBox1.Text += Environment.NewLine; 
            }
        }
    }