0

I have written a simple loop to get a factorial.However, the code seem to be neglecting the condition(n>=1) and i end u with zero as the n!.

The code works when i use (n >= 2) as opposed to (n >= 1).

class Program
{
    static void Main(string[] args)  
    {  
        int n;  
        n = int.Parse(Console.ReadLine());  

        decimal factorial = 1;
        Console.Write(" {0} * ", n);  

        do  
        {
            n--;
            factorial *= n;
            Console.Write(" * " + n);
        } while (n != 1);  

        Console.WriteLine("=" + factorial);    
     }  
 }  

If i put n = 10, i expect to get 10*9*8*7*6*5*4*3*2*1 = 3628800 instead, i get, 10*9*8*7*6*5*4*3*2*1*0 = 0

vc 74
  • 37,131
  • 7
  • 73
  • 89
  • 2
    I don't see a `n>=1` statement that could be neglected in this code. – Tobias Tengler Feb 09 '19 at 10:07
  • Assuming the test n!=1 was n>=1. When n =1 then the loop will run again because the condition is true and the first thing it does is decrease n to 0. The condition should be while n>1 – Bob Vale Feb 09 '19 at 10:13
  • Also you won't multiply by the first number because you decrease n before using it. If you remove the n-- and change the while to read `while (--n <= 1)` that should work. (The -- before n means decrement and then evaluate whereas `n--` is evaluate then decrement. If n ==10 then `--n` is 9 and `n--` is 10. Both modify n to be 9. – Bob Vale Feb 09 '19 at 10:15
  • You'd need to put n-- after the calculation in order to calculate only values covered by condition. – Dmytro Mukalov Feb 09 '19 at 10:17
  • `i get, 10*9*8*7*6*5*4*3*2*1*0 = 0` That is 100% not true. I ran your code, and got 362880 as the output, not 0. The issue isn't that you are multiplying it by 0. The issue is that you **aren't** multiplying it by 10. – mjwills Feb 09 '19 at 12:20
  • https://stackoverflow.com/a/3825263/34092 may also be of interest. – mjwills Feb 09 '19 at 12:58
  • Did you get this working @MikeCoulson? – mjwills Feb 10 '19 at 20:48

1 Answers1

1

Your looping logic was a little off, so I fixed it for you:

int n = int.Parse(Console.ReadLine()); // Maybe use int.TryParse here
decimal factorial = n;

Console.Write(n);

while (n > 1)
{
    n--;
    factorial *= n;
    Console.Write($" * {n}");
}

Console.WriteLine($" = {factorial}");

I'm also going to leave my preferred way of calculating Factorials (using Recursion) here:

public decimal CalculateFactorial(int number)
{
    if (number == 1)
        return 1;
    else
        return number * CalculateFactorial(number - 1);
}
Tobias Tengler
  • 6,848
  • 4
  • 20
  • 34