Reputation: 17
I've got the following loop:
public int multiply(int Z)
{
//Z=5
for (int i = 1; i <= Z; i++)
{
int Y=Z*i;
return Y;
//i wanna Y multiply x*4*3*2*1 all loops in one result
}
return Z;
}
What I'd like to know how to do is:
Create a new multiply int Y =Z*4*3*2*1 Result of multiply would be In Console Write Line:
("value for your loop is " +test.multiply(5));
value for your loop is 120
Can this be done by a for
loop or am I wrong?
Upvotes: 0
Views: 335
Reputation: 1277
What I think you actually mean is that you want to calculate the factorial of Z.
public int Factorial(int Z)
{
if (Z < 0) then return 0;
int res = 1;
for (int Y = 1; Y <= Z; Y++)
{
res *= Y;
}
return res;
}
Upvotes: 2
Reputation: 6142
Factorial using lambdas:
Func<int, int> factorial = null;
factorial = x => x <= 1 ? 1 : x * factorial(x-1);
var result = factorial(10);
:-)
Upvotes: 1
Reputation: 12535
This is called factorial:
public int Factorial(int num)
{
int factorial = 1;
for (int i = 2; i <= num; i++)
{
factorial *= i;
}
return factorial;
}
You can also get factorial recursively (this is basic exercise):
public int Factorial(int num)
{
if (num <= 1)
return 1;
return num * Factorial(num - 1);
}
Upvotes: 4
Reputation: 3109
public int multiply(int Z)
{
int result = Z;
for (int i = 1; i <= Z; i++)
{
int Z*=i;
}
return Z;
}
Upvotes: 0
Reputation: 14012
Yes:
public int multiply(int Z)
{
int Y = Z;
for (int i = Z; i > 0; i--)
{
Y *= i;
}
return Y;
}
Upvotes: 1