Solution for Exercise 9-15

ex0915

#include <stdio.h>

int main()
{
    float halfstep;

    halfstep = -5.0;
    while(halfstep <= 5.0)
    {
        printf("%.1f\n",halfstep);
        halfstep = halfstep + 0.5;
    }
    return(0);
}

Output

-5.0
-4.5
-4.0
-3.5
-3.0
-2.5
-2.0
-1.5
-1.0
-0.5
0.0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
4.0
4.5
5.0

Notes

* Because the increment through the loop is 0.5, a floating point variable must be used. The float variable halfstep is declared at Line 5.

* Line 7 initializes the halfstep variable to the value -5.0. The number contains a decimal and zero to ensure that the compiler recognizes it as a floating point value.

* Line 8 sets up the while loop by defining the end condition when the value of halfstep exceeds 5.0 — again, an immediate floating point value.

* Line 10 displays the current value of halfstep. I use the %.1f placeholder to keep output to one digit after the decimal, which is all that's necessary. If you use %f instead, each value is displayed with a lot of trailing zeros.

* Line 11 increments the value of variable halfstep by 0.5.