C++ Assignment 9
More loops and the line function

The line function draws a line from a point to a second point. It takes four arguments--the x & y coordinates of the first and second points. Remember that the top left corner of the screen is (0,0). The following line of code will draw a line from the center of the screen (320,240) to the center of the top of the screen (320,0), if the graphics window is set to 640 by 480

line (320,0,320,240);

We could make a pattern of lines with the following code:


#include "winbgim.h"

void DrawLines ();

int main ()
{
    initwindow(640,480);
    DrawLines();
    getch();
    closegraph();
    return 0;
}

void DrawLines ()
{
    setcolor(MAGENTA);
    line (320,0,320,240);
    line (320,30,350,240);
    line (320,60,380,240);
    line (320,90,410,240);
    line (320,120,440,240);
    line (320,150,470,240);
    line (320,180,500,240);
    line (320,210,530,240);
    line (320,240,560,240);
}

Clearly there is a better way to do this!

We are basically doing the same thing over and over again with a small change each time--an obvious place to use a loop.

Part One:

Write a program that will produce a 4-pointed star from a pattern of lines similar to the previous example. You should use the appropriate repetition structure in c++. You may want to include a delay in your loops to add a nice animation effect.

Part Two:

Experiment with the line function to create a design you find interesting and show it to the instructor. You may want to include the following optional functions:

kbhit() The "keyboard hit" function checks to see if a key has been pressed. If no key has been pressed it returns false. If a key has been pressed, it returns true. It is usually used with the ! (not) operator. Example:


#include "winbgim.h"

void main (void)
{
    initwindow(640,480);

    int nNum = 0;
    while(!kbhit())  //keep loop going until a key is pressed
    {
        line(0,nNum,640, 480 - nNum);
        nNum++;
        delay(50);
    }
    getch();
    closegraph();
    return 0;	
} 

rand() The random function generates a "pseudo-random" number between 0 and RAND_MAX (some huge number). rand() is generally used with modulus to get a random number within a certain range. For example:


#include <iostream.h>
#include <stdlib.h>        //include the random functions
#include <time.h>         //include the library of time functions
int  main ()
{
       srand(time(NULL));          //seed the random number generator
	cout<<rand()%100<<endl;		//displays a number between 0 and 99
       system("PAUSE");
       return 0;
} 
You can use random numbers to have your design at appear at different random places on the screen.