I want to use the for loop for my problem, not while. Is it possible to do the following?:
for(double i = 0; i < 10.0; i+0.25)
I want to add double values.
I want to use the for loop for my problem, not while. Is it possible to do the following?:
for(double i = 0; i < 10.0; i+0.25)
I want to add double values.
To prevent being bitten by artifacts of floating point arithmetic, you might want to use an integer loop variable and derive the floating point value you need inside your loop:
In
f indicates
float
The added
=
indicates a shortcut for i = i + 0.25;You can use
i += 0.25
instead.James's answer caught the most obvious error. But there is a subtler (and IMO more instructive) issue, in that floating point values should not be compared for (un)equality.
That loop is prone to problems, use just a integer value and compute the double value inside the loop; or, less elegant, give yourself some margin:
for(double i = 0; i < 9.99; i+=0.25)
Edit: the original comparison happens to work ok, because 0.25=1/4 is a power of 2. In any other case, it might not be exactly representable as a floating point number. An example of the (potential) problem:
prints 11 values:
For integer. We can use :
for (int i = 0; i < a.length; i += 2)
Same way we can do for other data types also.
The added = indicates a shortcut for i = i + 0.25;