Oscillation

Going back and forth happens frequently in the real world, and not just when you forget to pick up something at the store. Pendulums swing back and forth. The tide rises and falls. Politicians waffle.

In C, you can use the sin() function to obtain the natural sinus rhythm:

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

int main()
{
    float x;

    for(x=0.0;x<20.0;x+=0.5)
        printf("%f\n",
                sin(x)
              );

    return(0);
}

This code’s output displays values cascading from 0.0 to 1.0, back to 0.0, down to -1.0, and back up again. Thanks to mathematics I’m too impatient to explain, the values naturally switch directions; only one variable is needed in the code because the sin() function outputs the result within the range of -1.0 to 1.0.

You can emulate this type of behavior in your code. For example, say you need code that generates integer values between -5 and 5, cycling over and over. Here’s sample output:

 0  1  2  3  4  5  4  3  2  1  0 -1 -2 -3 -4 -5 -4 -3 -2 -1
 0  1  2  3  4  5  4  3  2  1  0 -1 -2 -3 -4 -5 -4 -3 -2 -1 
 0  1  2  3  4  5  4  3  2  1

Values to up to 5, then march down to -5 and back up to 5 again, over and over.

For this month’s Exercise, your task is to write code that outputs such an oscillating pattern of integer values. You can try to use trigonometric functions, but an easier solution is possible. Start at zero and bounce the output between 5 and -5, generating 20 numbers (as shown above).

View my solution here.

2 thoughts on “Oscillation

  1. I was thinking of writing a short program to print a console-based sine wave. I sketched out the solution using a 2D char array (or an array of strings) with the sine values -1 to +1 added and multiplied up to get indexes 0 to 20, and 0 to 360 degrees divided down to get indexes 0 to 36. I’d then set the sine value characters to ‘*’ and print them out.

    Having thought out a way of doing it I decided I couldn’t be bothered to actually code it!

    btw – do you know why M_PI is optional in math.h? It makes it effectively useless as you have to do #ifndef . . . when you need to use it. It would be better if it wasn’t there at all so you know you always need to #define it.

  2. In one of my books I had such a program, where asterisks printed out a sine wave vertically in text mode. I’ll see if I can dig it up somewhere.

Leave a Reply