Calculating factorials in C# using loops

14,377

Solution 1

Your loop assigns the square of the number to the result in a loop, and exits right away. You need to change it so that the result is repeatedly multiplied by numbers from 1 to N, inclusive.

Assign 1 to factorial, and multiply it by counter inthe loop:

factorial *= counter;

Don't forget to start your counter at 1.

Solution 2

The for loop doesn't make any sense at all! If you are looking for a factorial, then you have to multiply all the numbers from one to the given number. That would be:

int factorial = 1;

for (counter = 1; counter <= number; counter++)
{
    factorial = factorial * counter;

}

Console.WriteLine("The factorial of {0} is {1}", number, factorial);

This would calculate the factorial of one number. You would have to repeat it for all the numbers you wanted.

Share:
14,377

Related videos on Youtube

Sabotenderizer
Author by

Sabotenderizer

Updated on June 04, 2022

Comments

  • Sabotenderizer
    Sabotenderizer almost 2 years

    This is what I have so far:

    namespace factorials
    {
        class Program
        {
            static void Main(string[] args)
            {
                int number;
    
                do
                {
                    Console.WriteLine("What non-negative integer do you want to factorial?");
                    while (!int.TryParse(Console.ReadLine(), out number))
                        Console.WriteLine("Please enter a whole number only");
                    calculate(ref number);
                } while (number >= 0);
                Console.WriteLine("Please enter a non-negative number");
    
            }
            static void calculate(ref int number)
            {
                int factorial;
                int counter;
    
                for (counter = number; counter <= number; counter++)
                {
                    factorial = number * number;
                    Console.WriteLine("The factorial of {0} is {1}", number, factorial);
                }
    
        }
        }
        }
    

    Right now it just gives me the square of the numbers, not the factorial of them. How do I make it repeat the number of times as the input so it results in a factorial?

    Also I am not sure if it's necessary to limit the program to non-negative integers only but if I want to that part is just ending the program right there instead of looping back to the beginning.

  • rbr94
    rbr94 over 7 years
    Please provide some more explanations to your post