Does this for
loop ever stop?
for(int i=1; 1/i > 0; i++) {
}
If so, when and why? I was told that it stops, but I was given no reason for that.
Does this for
loop ever stop?
for(int i=1; 1/i > 0; i++) {
}
If so, when and why? I was told that it stops, but I was given no reason for that.
Yes.
First iteration: i = 1, 1/1 = 1 > 0, so it loops.
Second iteration: i = 2, 1/2 = 0 !> 0 (integer division), so it stops.
Details about integer division are documented in javadoc
Yes the for loop stops after one iteration. Dividing 1 by 2 in the second iteration will cause the for loop to stop because intergers don't record decimals meaning one divided by two will be 0 rather than .5.
1/2
is evaluated as an integer, and simply chops the decimal point. Hence 1/2 = 0
.
If one of those numbers was a floating point (ex. 1.0/2
or 1/2.0
), it would return the expected 0.5
.
in this code
for(int i=1; 1/i > 0; i++) {
//any code here
}
in your code
why the for loop stop in 1/2 because 1 integer and 2 integer
and integer / integer must = integer 1/2 = 0 (0.5 not integer)
if you use this code the for loop many many executed .
because int/float = float
1/1.0 =1 / 1/2.0= 0.5 / 1/3.0 = 0.33333 / 1/4.0 = 0.25 ...ect
for(float i=1; 1/i > 0; i++) {
//any code here
}
this is my first time posting and I am definitely a novice so if I provide incorrect information someone please correct me :).
My understanding is that because i and 1 are both of the type integer in the line:
for(int i=1; 1/i > 0; i++)
then your program will automatically perform integer division/arithmetic which results in the modulus or remainder being dropped. Therefore during the second iteration the remainder of 0.5 will be dropped resulting in 0 and thus termination of the loop.