I’m trying to find the factorial of a number in C#. (The factorial of five is this: 5! 5x4x3x2x1) The console displays "no output" even though I requested to print a variable. Some syntax may be wrong, too.
I would like if you guys could try to not use a different thing like arrays to print a value. Please use the while loop unless I need to change the way I am doing this.
If you would like, you can use methods, but I prefer not to in this scenario. I do not think a method is necessary right now. Share your feedback.
Does anyone know why it isn’t working? Please comment to help!
`
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int factorial = Convert.ToInt32(Console.ReadLine());
int final = 0;
int factorialCopy = factorial;
int five = 5;
while(factorial > -1)
{
int digitMinusOne = five - 1;
int multiplication = factorialCopy*digitMinusOne;
final = final + multiplication;
five = digitMinusOne;
factorialCopy = multiplication;
}
Console.WriteLine(final);
}
}
}
`
Any help would be appreciated. Thanks!
>Solution :
just like 500 – Internal Server Error said, when you use a While loop, you should always update the value of the evaluated variable inside the loop, so next time it evaluates the condition it can be a different result.
Plus I’m not sure if you’re using a correct condition in your while loop. That looks like it’s going to run forever.
I would do something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int factorial = Convert.ToInt32(Console.ReadLine());
// Init this in 1, to be able to do multiplication on it since the start.
int final = 1;
// You don't want to consider 0,
// You'd end up with 0 every single time
while(factorial > 0)
{
final = final * factorial;
// Here you assign factorial to the next number
factorial = factorial -1;
}
Console.WriteLine(final);
}
}
}
Hope that helps!