Solution for Exercise 11-15

ex1115

#include <stdio.h>
#include <math.h>

#define PI 3.14159
#define WAVELENGTH 70
#define PERIOD .1

int main()
{
    float graph,s,x;

    for(graph=0;graph<PI;graph+=PERIOD)
    {
        s = sin(graph);
        for(x=0;x<s*WAVELENGTH;x++)
            putchar('*');
        putchar('\n');
    }
    return(0);
}

Notes

* Don't sweat it if the trigonometry in this code boggles you.

* Here is the graphical representation of a sine wave:

Sine Wave

* The constant PI is needed because the C language trig functions deal with radians, not degrees. So in Line 12, the for loop goes from zero to PI radians, which is half a circle.

* You can make adjustments to the code by changing a few of the key values. I've defined those values as constants, which makes them easier to change:

* The constant WAVELENTH sets the height of the graph (left-to-right) as measured by screen columns. To make the graph more squat, change the value to something smaller.

* Technically speaking, the constant names used in this example are incorrect. The constant WAVELENGTH refers to the wave's amplitude, or it's "height" as measured left to right. The constant PERIOD is really the wavelength, or the breadth of the wave from top to bottom on the display.