# C loop with steps smaller than 1

So I'm wondering, how do I make sure that all steps in a loop are performed if the step size is smaller than 1? Take this loop for instance:

``for (float y, x = -1.0; x <= 1.0; x += 0.1) {y = (4*x*x*x) + (3*x*x) + (5*x) - 10;printf("x = %.2f, y = %.2f\n", x, y);}``

Output:

``x = -1.00, y = -16.00x = -0.90, y = -14.99x = -0.80, y = -14.13x = -0.70, y = -13.40x = -0.60, y = -12.78x = -0.50, y = -12.25x = -0.40, y = -11.78x = -0.30, y = -11.34x = -0.20, y = -10.91x = -0.10, y = -10.47x = 0.00, y = -10.00x = 0.10, y = -9.47x = 0.20, y = -8.85x = 0.30, y = -8.12x = 0.40, y = -7.26x = 0.50, y = -6.25x = 0.60, y = -5.06x = 0.70, y = -3.66x = 0.80, y = -2.03x = 0.90, y = -0.15``

I intend the loop to also run for x = 1, but as you can see it doesn't do that. I've heard that it's not safe to use floats as loop counters, as the float precision isn't exact. The fact that I'm using a float variable as the loop counter is probably the cause of my problem. So what solutions are there to my problem? Thanks in advance for your kind responses!

The problem, as you noted, is that you shouldn't use floats as loop counters. So multiply everything by 10 and use integers:

``````for (int x = -10; x <= 10; ++x) {
float y = (0.004*x*x*x) + (0.03*x*x) + (0.5*x) - 10;
printf("x = %.2f, y = %.2f\n", 0.1*x, y);
}
``````

Produces:

``````x = -1.00, y = -16.00
x = -0.90, y = -14.99
x = -0.80, y = -14.13
...
x = 0.90, y = -0.15
x = 1.00, y = 2.00
``````

as expected.

Perhaps even better: logically separate your loop variable from the meaningful stuff.

`````` for(int i = -10; i <= 10; ++i) {
float x = 0.1 * i;
float y = (4*x*x*x) + (3*x*x) + (5*x) - 10;
printf("x = %.2f, y = %.2f\n", x, y);
}
``````