CSCI 1300 - Exercise 3
Loops and BGI Graphics

What You'll Get from This Exercise

This exercise is to supplement your reading on loops. It also introduces you to the BGI collection of graphics functions that we'll use to draw objects from within a C++ program.

PC Labs in the
Engineering Center

CR 235    

CR 239

CR 244    

CR 252 (24 hours)

CH 107    

ME 107

Other campus sites are
listed at www.colorado.edu/its/labs.

Getting the first Demonstration Program

·         Start this exercise by opening Visual Studio and creating a new "CLR Empty Project."  Keep track of the directory where the project is located.  Once you've created the empty project, download the following file, and save it into that directory:

                                                    http://www.cs.colorado.edu/~main/cs1300/lab/loops.cxx

·         In Visual Studio, right-click on the "Source Files" folder in Solution Explorer window, and select "Add => Existing Item."  Find the "loops.cxx" file and include it in your project.

The Purpose of loops.cxx

·         The purpose of loops.cxx is to let you step through a couple different kinds of loops. Apart from that, the program doesn’t really do anything useful.  Go ahead and open the loops.cxx file. You can look through the code to get an idea of what the program is doing. Run the program once and give the W response, and run it a second time with the F response. Running the program in this way won’t be particularly enlightening, but using the debugger you can get more out of the program.

Putting some breakpoints in the program

·         The loops program will be most useful if you use the debugger to run the program with two breakpoints. Remember from Exercise 2 that a breakpoint is a statement in your program where you want the program to stop so you can examine the state of affairs more closely. To set the first breakpoint, move through the file until you see the line in the main program which calls a function named savings_time:

·                 case ‘W’: case ‘w’: // Call savings_time
     many_years = savings_time(50, 100, 0.10);

Click on the grey column to the left of the "many_years..." line shown above (which is the line that calls the savings_time function). You should see a red dot in the column indicating a breakpoint at this line, so that when the program executes it will stop here to let you examine matters.

Next, move down to the line that calls the second function, called future_balance. The line looks like this:

  case ‘F’: case ‘f’: // Call future_balance
      final_balance = future_balance(50, 0.10, 5);

Set a second breakpoint on this "final_balance..." line.

Running the Program up to the Breakpoint

·         With the two breakpoints in place, you can run the program in the usual way (F5, "Start Debugging", or the button). When you are asked which kind of loop to see, respond with W. The program will then run until it reaches the breakpoint at the statement "many_years = savings_time(50, 100, 0.10);". This line calls the savings_time function to determine how many years are required to increase a balance of $50 to a goal of $100 with an annual interest rate of 10%. We want to step into this function and watch the lines execute one at a time to see how a while-loop works. When you executing a program (in Debug mode), use the F11 key (or the  button) to step into a function.  Once you're inside the function, use the F10 key to step over () each command, line by line, until you exit the function. (Note the difference between the "step into" and "step over" commands. The "step over" command executes an entire line, even if it calls a function, without stepping through any functions line-by-line.)

Setting Watches

·         In a moment you will step through the savings_time function, one line at a time. But first, let’s set things up to watch the values of a few variables. Put watches on the local variables balance, goal and years.

You should now continue executing the savings_time function one line at a time, using the F10 command. The function’s first statement, years=0, is now highlighted and ready to execute. Press F10 and the statement will execute, setting the value of years to zero in the Watch window. The highlighted line moves down to the first line of the while-loop:

    while (balance < goal)

Seeing the While-loop in Action

·         The loop that we are about to execute will calculate how many years are needed to increase the balance ($50.00) to the goal ($100.00) at the stated interest rate (10%). At the start of the loop’s execution, the highlighted line is the while-statement:

    while (balance < goal)

This is the statement that controls the while-loop. The statement indicates that the loop should continue as long as balance is less than goal. At the moment, balance ($50) is less than goal ($100), so the loop will continue executing. To continue this execution, press "step over" (F10) again. The cursor moves to the first assignment statement in the body of the loop (balance = ...). At this point, you should execute the two lines of the loop’s body by giving two F10 commands. These statements will increase balance to $55, and increase years to 1. The highlight will once again be at the first line of the while-loop:

    while (balance < goal)

The balance ($55) is still less than the goal ($100), so the loop continues. Execute three more lines, and once more you are back at the top of the loop. This is what a while-loop does: It goes around and around, always controlled by the expression at the top of the loop. The current balance ($60.5) is still less than the goal ($100), so the loop continues. again. Keep executing, keeping an eye on the value of the balance. Stop when you notice that the balance is larger than 100. At this point, the balance should be 107.1794, and years is 7.

The program is still executing inside the loop. The highlighted statement:

    years = years + 1;

is about to be executed. Now, at this point, balance is bigger than goal--so you might be thinking that the loop should stop. But it won’t--not quite yet. The loop must always continue until it reaches the controlling statement at the top. At that point, the loop uses the control statement to determine whether to continue.

For our example, execute one more line. The value of years increases to 8, and we are back at the top of the loop. Now, balance is less than goal, so the loop will end. To see this, execute one more line and the highlighted statement moves after the loop to: return years; This is the function’s return statement, which returns 8 (the current value of years). In other words, it took 8 years to increase $50 to at least $100 at a 10% interest rate.

You can continue pressing F10 (or just press F5 to continue without stepping line-by-line) to complete the execution of the program.

Running to the Second Breakpoint

·         You can now run the program a second time. This time you should answer F when you are asked what kind of loop you want to see. The program will run to line that calls the future_balance function:

    final_balance = future_balance(50, 0.10, 5);

Stepping into the future_balance Function

·         This function call computes how much money will be in an account that starts with a balance of $50 and earns 10% annual interest for 5 years.  To step into this function, press the F11 key.  The compiler jumps to the first line of future_balance, displaying the values of the arguments and local variables.

Seeing the For-loop in Action

·         Now we can see the statements of the function’s for loop executed one at a time. Give the n command once, and the highlighted line jumps into the function’s body. Here’s what you see on the screen:

·                    for (i=0;
·                        i<years;
·                        i++
        )

These four lines combined are actually the control statement of a for-loop. Normally the control statement would be written on a single line, like this: for (i=0; i<years; i++)—but we have broken it into separate lines so that the debugger can show precisely how the different parts of the control statement are executed. In order to see this execution more clearly, put a watch on the local variable i, and then move to the next step of this exercise.

The Initialization Clause of the For-Loop

·         The control statement of every for-loop has three parts, separated by semi-colons. The first part is the initialization clause. For our example, the initialization clause is the highlighted statement i=0; The initialization clause is always executed once when the for-loop begins. For our example, execute one line now; the assignment i=0 will be executed, and i changes to zero in the watch window. The highlight moves to the second clause in the for-loop’s control statement.

The Repetition Test Condition

·         The second part of a for-loop’s control statement is the repetition test condition. This is a test, such as our test  i<years. The test is executed each time before the body of the loop is about to begin. If the test is true, then the loop continues. If the test fails, then the loop stops. In our example, the test i<years is true. So, press F10 to execute this test, and the debugger will move the highlighted statement to the inside of the loop’s body.

Executing the Body of the For Loop, and the Update Clause

·         The body of our for-loop is now ready to be executed. This body consists of two assignment statements, so you should press F10 twice to execute these statements. After the second assignment statement, the debugger will move the cursor to the third clause in the for-loop’s control statement. This clause, which is written i++ in our example, is the update clause. The update clause is executed each time the body of the loop finishes. In our example, the update clause i++ adds one to the value of i. Press n to execute the update clause, and the highlight moves back to the repetition test condition. You have now seen the complete cycle of a for-loop, which looks like this in a diagram:

Execute the For-loop to Completion

·         At this point you can use the F10 key to execute our for-loop to completion. As you are executing the loop, pause for a moment whenever the cursor reaches the repetition test condition (i<years). This condition determines whether the loop should continue. When the condition becomes false, the loop will end. When the loop ends, you can continue executing the program to completion.

Introduction to BGI

·         There's one more brief task before the end of this exercise. The task introduces you to the graphics library that we'll use throughout the semester.  In order to use the BGI (Borland Graphics Interface) library, you need to download the following file onto your machine (preferably to the desktop, where you can easily access it):

            BGI Graphics.zip

·         You should right-click the file and select "Extract Here" to unpack the files.  The newly created directory includes all the files we'll need (including the BGI Libraries and a pre-set project already set up to use them) in order to create a BGI graphics program in Visual Studio.

o        NOTE FOR HOME USE:   If you're working from home using Visual Studio Express Edition (not the Professional Edition installed in the labs), you will first need to install a number of other libraries before you can use any of the BGI functions.  In order to do this, go to http://msdn.microsoft.com/vstudio/express/visualc/usingpsdk/ and install the Microsoft "Platform SDK" (Software Development Kit).  This kit includes a number of libraries allowing you to use Windows features that aren't automatically included in the C++ language.  Once you have the SDK installed, the BGI Library should work on your machine.

·         Inside Visual Studio, select "File => Close Solution" to close the "loops" program.  Then select "File => Open => Project/Solution", and open the "BGI Project.sln" file inside the directory you just downloaded.  This file includes a BGI Project that is already pre-set to use the BGI library functions.

Running the "bgidemo0" Program

·         Go ahead and build the program.  You may notice a number of warnings;  this is due to the fact that the "bgidemo0" program was last written in 1993, and some of the function calls are out-of-date.  You can ignore these warnings.  If you have errors that prevent the program from building, please let us know so we can help you.

·         Run the program.  You will see a console window (like always) followed by a small graphics window.  Press "Enter" to traverse from one graphics screen to the next, and you'll get an idea of the basic functionality of the BGI library.  There are between 3 & 4 dozen screens in all... the last screen contains the message

                                "That's all, folks!"

A Simpler Graphics Program for You To Modify

·         Whenever you run a BGI program, you'll have to compile and run it as you did with the bgidemo program... the easiest way to do that is to re-use the "BGI Project" we've already provided.  In order to do this, simply right-click on the "bgidemo0.cxx" file in Visual Studio, and select "Remove."  Don't delete the file, just remove it from the project.  Next, right-click on the "Source Files" folder and select "Add => Existing Item."  Find the file called "bgismall.cxx" and include it in your project.  Writing a BGI program requires some techniques that are more easily illustrated with a smaller graphics program like bgismall.cxx.  Build and run this file now.  Then bring up the source code in the window and notice these things:

1.      To access the BGI library, the program includes the graphics.h header file with the directive

#include <graphics.h>

2.      When a program begins execution, it opens a graphics window where the drawing will occur. Text input and output may still go through the original console window (using cin or cout), or it may go to the graphics window using other commands.

3.      The program needs to call the initwindow(...) function to initialize the graphics screen and begin graphics mode. In bgismall.cxx, the main program calls initwindow(450, 300), which creates a graphics window that is 450 pixels wide and 300 pixels high.

4.      The graphics screen consists of a grid of pixels which can be thought of as points of light on the screen. For smaller monitors, the grid usually has a maximum of 640 pixels in the horizontal direction ( numbered 0 to 639 from left to right ) and 480 pixels in the vertical direction ( numbered 0 to 479 from top to bottom). If we take x to be our name for the coordinate in the horizontal direction and y for the vertical direction, then the origin ( x = 0, y = 0 ) of the numbered grid is in the upper left corner of the screen. The x-coordinate increases as one moves to the right. The y-coordinate increases as one moves down the screen. The direction for increasing y is opposite to our usual practice, and will probably cause much hardship until everyone becomes used to it.

In general, the code that you write should not depend on a particular screen size. Instead, you should call the BGI functions getmaxx() and getmaxy() to get the maximum x and y pixel numbers.

5.      Once the program in in graphics mode, there are nearly 100 different BGI functions that can be used. The bgismall program uses these functions:

·         putpixel(x, y, color) -- draws a pixel in a particular color at a given x and y location.

·         setcolor(color) -- determines the color for subsequent drawing functions such as line and circle.

·         line(x1, y1, x2, y2) -- draws a line from (x1,y1) to (x2,y2).

·         circle(x, y, radius) -- draws a circle with center (x,y) and the specified radius.

These graphics functions may also be called from within other functions (such as within the triangle function that is part of bgismall.cxx).

6.      When the program is finished drawing it should call the function getch(). This pauses for the user to press the return key (with the mouse focus in the graphics window). Then call closegraph() to close the graphics window.

More BGI Functionss

·        Play around with the bgismall.cxx program a little bit, making it draw some new lines or use new colors. Further BGI information is available at www.cs.colorado.edu/~main/cs1300/doc/bgi/bgi.html). A complete list of the BGI functions is available at www.cs.colorado.edu/~main/cs1300/doc/bgi/index.html).