Sabotenderizer - 4 months ago 40

C# Question

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.

Answer

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.