Reputation: 1
I can't get this for loop to execute the factorial it is supposed to. It seems to only be looping once.
static void Main(string[] args)
{
int a;
int total=1;
Console.WriteLine("Please enter any number");
a = Convert.ToInt32 (Console.ReadLine());
total = a;
for (int intcount = a; intcount<= 1; intcount--)
{
total *= intcount;
}
Console.WriteLine("Factorial of number '{0}' is '{1}'", a, total);
Console.ReadKey();
Upvotes: 0
Views: 3697
Reputation: 16813
Full solution is here! tested and works. Recursive Implementation as well as basic implementation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication50
{
class Program
{
static void Main(string[] args)
{
NumberManipulator manipulator = new NumberManipulator();
Console.WriteLine("Please Enter Factorial Number:");
int a= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("---Basic Calling--");
Console.WriteLine("Factorial of {0} is: {1}" ,a, manipulator.factorial(a));
Console.WriteLine("--Recursively Calling--");
Console.WriteLine("Factorial of {0} is: {1}", a, manipulator.recursively(a));
Console.ReadLine();
}
}
class NumberManipulator
{
public int factorial(int num)
{
int result=1;
int b = 1;
do
{
result = result * b;
Console.WriteLine(result);
b++;
} while (num >= b);
return result;
}
public int recursively(int num)
{
if (num <= 1)
{
return 1;
}
else
{
return recursively(num - 1) * num;
}
}
}
}
Upvotes: 0
Reputation: 700562
Loop while the value is larger than 1:
for (int intcount = a; intcount > 1; intcount--) {
total *= intcount;
}
Alternatively, loop up to the value:
for (int intcount = 2; intcount <= a; intcount++) {
total *= intcount;
}
Upvotes: 0
Reputation: 14929
total = 0;
for (int intcount = 1; intcount<= a; intcount++)
{
total *= intcount;
}
or
total = a;
for (int intcount = a; intcount>= 1; intcount--)
{
total *= intcount;
}
Upvotes: 0
Reputation: 23636
You should change initialization from total = a
to total = 1
and intcount<= 1
to intcount > 1
like this:
var a = 5;
var total = 1;
for (int intcount = a; intcount > 1; intcount--)
{
total *= intcount;
}
Console.WriteLine (total);//prints 120
Upvotes: 0
Reputation: 887767
intcount<= 1
This is false as soon as you start your loop, so the loop exits immediately.
You probably want to loop while that number is more than 1.
Upvotes: 5