Ezra Boyd Ezra Boyd - 8 months ago 76
C# Question

How to return a value from a for statement in a method in c#

I can't figure out why this code can't return

result
in the factorial method. Any help would be appreciated.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CalculatorProgram
{
class Program
{
static void Main(string[] args)
{
Console.Write("What is the first number:\n> ");
decimal x = Convert.ToDecimal(Console.ReadLine());

Console.Write("What is the second integer:\n> ");
decimal y = Convert.ToDecimal(Console.ReadLine());

Console.Write("What is the operation that you would like to use?
Enter + , - , * , / , or ! :\n> ");
string operation = Console.ReadLine();

if (operation == "!")
{
Console.Write("Which number would you like to use?\n> ");
int num = int.Parse(Console.ReadLine());
Console.WriteLine("{0}! = {1}", num, Factorial(num));
}

}
private static int Factorial(int a)
{
int result;
for (int i = 1; i < a + 1; i++ )
{
result = a * i;
}
return result;
}


}
}

Answer Source

result = a * i; is incorrect.

It should be something like result = result * i;, with result initialised to 1: i.e. change int result; to int result = 1;.

Currently you're evaluating a * a.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download