Reputation: 21
I am learning Java and discovering that a little bit of knowledge is confusing. The goal is to write a method that is the equivalent of the n! function. I am using a for loop to multiply a variable declared outside the method. All I get back is 0.
What am I doing wrong?
//
// Complete the method to return the product of
// all the numbers 1 to the parameter n (inclusive)
// @ param n
// @ return n!
public class MathUtil
{
public int total;
public int product(int n)
{
for (int i = 1; i == n; i ++)
{
total = total * i;
}
return total;
}
}
Upvotes: 0
Views: 7279
Reputation: 40036
There is actually a lot of problems in your code:
total
to a reasonable value. So here is a slightly improved version
public class MathUtil
{
//
// Complete the method to return the product of
// all the numbers 1 to the parameter n (inclusive)
// @ param n
// @ return n!
public static int factorial(int n)
{
int total = 1;
for (int i = 1; i <= n; i ++)
{
total = total * i;
}
return total;
}
}
so that you can call it as MathUtil.product(123)
instead of some weird new MathUtil().product(123)
Personally I would rather do something like
result = n;
while (--n > 0) {
result *= n;
}
return result;
Upvotes: 4
Reputation: 998
public int total = 1;
public int product(int n) {
for (int i = 1; i <= n; i++) {
total = total * i;
}
return total;
}
you havent initialized total. It defaults to 0. Then when you multiple anything with total, you get 0 as result
Upvotes: 1
Reputation: 1694
You are missing the initialization. Now I added the default value to 1. And you also have to change the condition. The for loop has to go on as long as the var i is smaller or equal to n.
public class MathUtil
{
public int total = 1;
public int product(int n)
{
for (int i = 1; i <= n; i ++)
{
total = total * i;
}
return total;
}
}
Upvotes: 2
Reputation: 21
you didn't initialized total, therefore it's 0. Whenever you multiply 0 with anything, you will get 0 as result.
Upvotes: 1