954,529 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Calculating a factorial of a number using C#

Hi,

I am having trouble writing the code to work for my C# .Net assignment.

I already design the form and now I have to get the code to work for my program. The problem I am having is if I put a number in my design form other than (1) the factorial comes back as (1.00000000000). I am not getting the correct answer. Here is my code:

private void btnCalculae_Click(object sender, System.EventArgs e)
        {
            long number = Convert.ToInt64 (txtNumber.Text);
            long factorial = 1;
               lblFactorial.Text = factorial.ToString("n20");
            
            // calculate factorial
    
            while ( number > 0 && number <= 20)
            {
                factorial *= number;
                number++;
            } // end while loop

            txtNumber.Text = "";
            txtNumber.Focus();
        }

        private void btnExit_Click(object sender, System.EventArgs e)
        {
           this.Close();
        }
    }
}


What am I doing wrong!!!!!!!! Please help

phephe
Newbie Poster
1 post since Jul 2006
Reputation Points: 10
Solved Threads: 0
 

Hi,

You must put the lblFactorial.Text = factorial.ToString("n20"); after the while loop.Loren Soth

Lord Soth
Posting Whiz in Training
233 posts since Mar 2006
Reputation Points: 28
Solved Threads: 4
 

public int fact(int x)
{
int fact=1;
int i=1;
while (i<=x)
{
fact = fact * i;
i++;

}
return fact;
}

pass by

int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(this.fact(n));

}

hajaworld
Newbie Poster
1 post since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

Or do it recursively : (this is a classic.)

public int fact(int n)
{
    if (n==0) return 1;
    else return n*fact(n-1)
}

Console.WriteLine("Type a number up to 20:");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(this.fact(n));
ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

int fact(int rank)
{
for(int i = 1; i

Jugortha
Junior Poster
172 posts since Oct 2007
Reputation Points: 11
Solved Threads: 16
 

Jugortha, before you post any code should you not test it yourself?
First: In C#, when you declare a variable in a for loop (in this case i) it is only known in the for loop not outside it(strict scoping rules in C#, I like that)
The return statement has not the faintest idea what i is.
Second: What's the use of incrementing a variable i in a for loop and multiplying it by one? It certainly will not give you a factorial!

ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

I think I know what he meant but as ddanbe has said, the code supplied produces nothing other than compilation errors and logic errors.

LizR
Posting Virtuoso
1,791 posts since Aug 2008
Reputation Points: 196
Solved Threads: 190
 

What are we doing here?
This thread has been started july 2006! (I just noticed.)
For all we know phephe might have left the Earth and moved to Mars.

ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

Someone probably googled and thought hey I can help with that.

LizR
Posting Virtuoso
1,791 posts since Aug 2008
Reputation Points: 196
Solved Threads: 190
 

I apologize this code will work for sure

long Factoriel(long n)
{
return n > 1?n * Factoriel(n-1):1;
}

I used the recursive method

If you want to get the factoriel of a given number you just call
Factoriel(number);

Jugortha
Junior Poster
172 posts since Oct 2007
Reputation Points: 11
Solved Threads: 16
 

hello,

• The user enters a number and clicks the Calculate button or presses the Enter key to activate that button.
• The program calculates the factorial of the number and displays it in a label on the form.
• The factorial of an integer is that integer multiplied by every positive integer less than itself. A factorial number is identified by an exclamation point following the number. Here’s how you calculate the factorial of the numbers 1 through 5:
1! = 1 which equals 1
2! = 2 * 1 which equals 2
3! = 3 * 2 * 1 which equals 6
4! = 4 * 3 * 2 * 1 which equals 24
5! = 5 * 4 * 3 * 2 * 1 which equals 120

• The application should return an accurate value for integers from 1 to 20. The factorial of the number 20 is 2,432,902,008,176,640,000. (If you enter a number larger than 20, a factorial will still be displayed, but it won’t be accurate.)
• The application assumes that the user enters a valid integer from 1 to 20.
• The application should format the factorial with commas, but no decimal places
please reply me i have submission tomorrow..

pinal patel
Newbie Poster
1 post since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

Holy resurrection, this thread is almost 5 years old.

That said, how to calculate a factorial has already been given. Since you are doing small number factorials (20 is small) the methods here will be fast enough. All you need to do is figure out what numeric type to use that will hold a value of 2.5 quintillion.

Momerath
Nearly a Senior Poster
3,386 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558
 

TRY

THIS CODE IN CONSOLE APLICATION

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static int factorial(int number)
{
if (number <= 1)
return 1;
else return number * factorial(number - 1);


}


static void Main(string[] args)
{
Console.WriteLine("The Factorial of 5 is {0}\n", factorial(5));
Console.WriteLine("The Factorial of 10 is {0} \n",factorial(10));

Console.ReadLine();
}
}
}

VIKRAM KHATRI
Newbie Poster
1 post since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

This thread never gonna die! :D

Antenka
Posting Whiz
362 posts since Nov 2008
Reputation Points: 293
Solved Threads: 82
 

long factorial = 1;//My friend you are assigning 1 to factorial and converting it into string with("20")....
//U can correct this mistake by assigning long number to long factorial..long factorial =number;label1.Text = factorial.ToString("n20");

Nazook Nazeer
Newbie Poster
1 post since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

Hello,
I am happy to see this, I am a New student of C#, This Problem is what I used as my Assignment on Friday, Below is the Simple Code, that I Used for it, Hope it work for you as well,.... thank

private void btnCalculate_Click(object sender, EventArgs e)
    {
        bool flag;
        double start;
        double formula;
        double answer;
        double j;

        flag = double.TryParse(txtNumberTo.Text, out start);  // This is to make sure that User Input is Digit Data.
        if(flag==false)
        {
            MessageBox.Show("Numeric Data Only", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            txtNumberTo.Focus();
            txtNumberTo.Clear();
            return;
        }

        answer = start;  
        for (j = 0; j < start; j++) // This is the Code that Do the Factorial Work.
        {
            formula = start - j;
            answer *= formula;
        }
        lblAnswer.Text = start.ToString() + "!" + " = " + answer.ToString(); // This will be your Output, likr N! = XXXX eg 5! = 120
    }
jnmisa
Newbie Poster
15 posts since Nov 2011
Reputation Points: 10
Solved Threads: 1
 

I write calculator that include "0-9,/,*,-,+,(, )" but I don't know how to insert "(,)" of coding.
I insert but can't use it who have an idea?

larnoy
Newbie Poster
1 post since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

Could somebody help for the problem is I code for invalid number input message but it won't show up message "invalid numbe"?
Here my code:

private void Calculate_Click(object sender, EventArgs e)
{
long number = Convert.ToInt64(txtNumber.Text); // get number input from text box number
long factorial = 1;

// calculate factorial

while ( number > 0 && number <= 20 )
{
factorial *= number;
number--;

} // end while loop


if (number < 0 && number > 20)
{
lblFactorial.Text = "invalid number";
}

{
lblFactorial.Text = factorial.ToString("n0");

}
}

private void Exit_Click(object sender, EventArgs e)
{
this.Close();
}

private void btnClear_Click(object sender, EventArgs e)
{
txtNumber.Clear();

}

}
}

LongVong
Newbie Poster
4 posts since Feb 2012
Reputation Points: 7
Solved Threads: 0
 

You need to check if it is invalid *before* you do your factorial calculation (since that reduces the input number to zero). And please let this thread die.

Momerath
Nearly a Senior Poster
3,386 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558
 

Hi LongVong, welcome.
You would be more welcome if you:
===> Used code tags
===> Don't resurect old threads.
AS of your problem:
Look at this :if (number < 0 && number > 20)
This if will only happen if your number is smaller than 0 and bigger than 20???
Use || instead.

ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You