I have such for loop and when step is (0;1) it becomes infinite. If step is [1;..) it works well.
public interface FindMinI {
double function(double x);
static double findMinOfFuncOnInterval(int begin, int end, double step, FindMinI func)
{
double min = Double.MAX_VALUE;
for (int i = begin; i <= end ; i += step) {
if(func.function(i) <= min)
min = func.function(i);
}
return min;
}
}
As we know that all the parts of the 'for' loop are optional, and in the above for loop, we have not mentioned any condition; so, this loop will execute infinite times. Let's understand through an example. In the above code, we run the 'for' loop infinite times, so "Hello javatpoint" will be displayed infinitely.
You cannot make an infinite foreach loop. foreach is specifically for iterating through a collection. If that's not what you want, you should not be using foreach .
An infinite loop is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over.
An Infinite Loop in Python is a continuous repetitive conditional loop that gets executed until an external factor interferes in the execution flow, like insufficient CPU memory, a failed feature/ error code that stopped the execution, or a new feature in the other legacy systems that needs code integration.
If you try with step between (0,1)
this will be casted to int when adding to i
, as a result you will add 0
to i
in every iteration which will lead to infinite loop!
It will be infinite, because if step
is 0 then adding zero to i would do nothing. No incrementation means infinite loop.
If step is 0 you're adding 0 to i
meaning there's nothing being added to the value, and it gets stuck as infinite.
Since you supply step as a double, having values like 0.0001 is possible. However, since i
is an integer the conversion is made from double to int, and 0.0001 -> 0. When you cast a value that's less than 1 and more than 0 as an integer, it becomes 0.
Change i
to double
and you can use decimal values to increment.
Alternatively, you could change step
to int
, but you wouldn't be able to use decimal steps in that case
A similar situation can be found with division or multiplication to demonstrate the double example:
(int) (500 * 0.0001) -> 0.05 as an integer = 0
So when you add a double step with a decimal value (exclusively a decimal value) to an integer, step becomes 0
, 0
is added to i
and it becomes infinite.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With