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
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
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
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