Search code examples
c#factorial

How to take the Product of a List?


I am trying to make a factorial calculator in C#, but I am having difficulties taking the product of all the numbers after I have collected them into a list.

        List<int> myList = new List<int>();

        Console.WriteLine("My Job is to take the factorial of the number you give");
        Console.WriteLine("What is the number?");
        string A = Console.ReadLine();
        int C = Convert.ToInt32(A);
        T:
        myList.Add(C);
        C--;

        if (C == 0) goto End;
        goto T;
    End:
        // This is where the problem is,
        // i don't know of a way to take to product of the list "myList"
        //Any Ideas?
        int total = myList.product();
        Console.WriteLine(" = {0}", total);
        Console.ReadLine();

Solution

  • You don't need a list to do a factorial:

    Console.WriteLine("My Job is to take the factorial of the number you give");
    Console.WriteLine("What is the number?");
    int c = Convert.ToInt32(Console.ReadLine());
    int total = 1;
    
    for (int i = 2; i < c; i++)
    {
        total *= i;
    }
    
    Console.WriteLine(total.ToString());
    Console.ReadLine();