Question

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?

Was it helpful?

Solution

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;
}

OTHER TIPS

This is called factorial:

public int Factorial(int num)
{
    int factorial = 1;

    for (int i = 2; i <= num; i++)
    {
        factorial *= i;
    }

    return factorial;
}

Demo

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);
}

Demo

Yes:

public int multiply(int Z)
{
    int Y = Z;

    for (int i = Z; i > 0; i--)
    {
         Y *= i;
    }

    return Y;
}

Factorial using lambdas:

Func<int, int> factorial = null;
factorial = x => x <= 1 ? 1 : x * factorial(x-1);
var result = factorial(10);

:-)

public int multiply(int Z)
{
    int result = Z;
    for (int i = 1; i <= Z; i++)
    {
        int Z*=i;
    }
    return Z;
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top