for(i=1;i<=10;i++) {
result = factorial(i);
out.println(result);
}
static long factorial (int n) {
int i;
long result=1;
for(i=1;i<=n;i++) {
result *= i;
}
return result;
}
method: factorial
Started by hawil, Jul 07 2010 06:54 AM
6 replies to this topic
#1
Posted 07 July 2010 - 06:54 AM
i traced the code and i got the how it works, the only thing i can't get is what is the purpose of int n? as i see, n is not being incremented.
|
|
|
#2
Posted 07 July 2010 - 10:07 AM
n determines how many times it loops. It shouldn't be incremented. It's just a maximum value.
#3
Posted 12 July 2010 - 05:40 AM
how come it does not go infinite? is that a built-in code for java?
#4
Posted 12 July 2010 - 10:44 PM
Assume n==2
Note that i++ is the same as i+=1
for(i=1;i<=n;i++)
i=1 -> for the first time
i<n -> condition checked every loop
i++ -> action done after every loop
First loop:
i==1
i<=n ? true
do result *= i
end of loop, i++,
Second loop:
i==2
i<=n ? true
do result *= i
end of loop, i++,
Third loop:
i==3
i<=n ? false
Leave the for-loop.
Note that i++ is the same as i+=1
for(i=1;i<=n;i++)
i=1 -> for the first time
i<n -> condition checked every loop
i++ -> action done after every loop
First loop:
i==1
i<=n ? true
do result *= i
end of loop, i++,
Second loop:
i==2
i<=n ? true
do result *= i
end of loop, i++,
Third loop:
i==3
i<=n ? false
Leave the for-loop.
#5
Posted 13 July 2010 - 04:25 AM
for that case the n has a value. in the code i provided the n has no values. xd sorry, really confused.
#6
Posted 13 July 2010 - 05:04 AM
n must have a value or the program will crash upon reaching the for-loop. I'm guessing that that will result in a NullReferenceException.
In your code you can't reach it without giving n a value:
...untill 10...
In your code you can't reach it without giving n a value:
for(i=1;i<=10;i++) {
result = factorial(i); --> [B]here you pass the value of i to factorial[/B]
out.println(result);
}
static long factorial (int n) { --> [B]here the i comes in, and is named n in this method[/B]
int i;
long result=1;
for(i=1;i<=n;i++) {
result *= i;
}
return result;
}So during the run you will loop 10 times herefor(i=1;i<=10;i++) {
result = factorial(i);
out.println(result);
}Which will result in:result = factorial(1); --> n will be 1 out.println(result); result = factorial(2); --> n will be 2 out.println(result); result = factorial(3); --> n will be 3 out.println(result); result = factorial(4); --> n will be 4 out.println(result); result = factorial(5); --> n will be 5 out.println(result);...
...untill 10...
#7
Posted 14 July 2010 - 04:36 AM
java can do that? waw! now i understand.. thank you very much. the n really confused me..


Sign In
Create Account


Back to top









