This lab can only be done in the Friend Center clusters unless (very unlikely) you have Visual Basic installed on your own machine.
While typing a paper into your favorite word processor, or perhaps while playing the hottest new computer game, you might have at some point wondered: how do people create these great programs? The answer, of course, is with programming languages. Programming languages provide a way to express computer algorithms in a form that is both convenient for humans yet easily translated into a computer's machine language.
In class, we have studied the very low-level instructions that the computer itself understands, and talked about a variety of programming languages, much easier for people to use, that are translated by a program into machine instructions. There are many such languages, each with its own good and bad points, and often noisy adherents and detractors.
Visual Basic, the topic of this lab and the next one, is one of the most widely used languages. Part of the reason for its popularity is that it makes it quite easy to create graphical user interfaces, that is, the kind of interface with pull-down and pop-up menus, buttons, sliders, scroll bars, and the like. VB is not the best language for everything -- it isn't really meant for big programs, nor ones where speed of operation is paramount, and it only runs on Microsoft environments, which sometimes matters. But it's a very good tool for learning and for making prototypes.
Visual Basic is also embedded in other tools, providing a powerful and flexible extension mechanism: you can write VB programs that run within and control Word, Excel, Powerpoint, and other major software systems, augmenting their capabilities or tailoring them to your needs. This mechanism is also, unfortunately, at the heart of some common computer virus attacks, including the Melissa virus that struck in March, 1999, or the Anna Kournikova virus that struck a year later.
In this lab (and the next one) you will explore Visual Basic. VB is a descendant of the original BASIC language developed at Dartmouth in 1964 by John Kemeny ('47, *49) and Tom Kurtz (*56). We do not expect you to become full-fledged VB programmers, but you will do enough to get some understanding of what programs look like and what is involved in taking an algorithm and turning it into a precise program implementing that algorithm.
There is an enormous amount of Visual Basic information on the Web, and thousands of books. One useful place to look is at this tutorial on the VB environment. The Visual Basic environment that you will be running also has extensive built-in help, which you should become familiar with.
Visual Basic has three major components:
Some of the components have been around a long time; these include functions and subroutines for doing mathematical operations (square root, for example), reading information from files and writing it to files, manipulating strings of characters (like finding or replacing a word within a sentence).
The newer components are mostly focused on user interfaces: buttons, scrollbars, menus, text display areas. This is one aspect of the "visual" part of VB. These components are usually called objects; they have properties that can be set and changed (size, color, caption, etc.), methods that cause them to do something, and events or external stimuli, like pushing a button, that they respond to.
Finally, it is possible to include a vast range of components from the Windows environment itself; you can control a spreadsheet like Excel, or a word processor like Word, or a browser like Internet Explorer from within a VB program. We won't get into that here, but it gives some hint of the power that is near to hand. Much modern programming in fact involves assembling of large components in this way.
You can run your program as you write it, in a controlled environment provided by VB, so that if something goes wrong, you are told quickly and often quite accurately what is wrong. And as we mentioned, there is an extensive help system to give rules and examples.
Once you are using VB, you can access help for a specific entity on the screen by putting the cursor on it, then pushing the F1 key on the keyboard; this should bring up context-sensitive help.
This will all sound somewhat overwhelming, but it will become clearer. In this section, we're going to create the simplest possible VB program and run it. All it will do is display a single button, labeled Quit; when you press the button, the program will quit. But this trivial example will clarify much of the process, and let you move on to bigger things.
Start VB by Start / Programs / Microsoft Visual Studio 6.0 / Microsoft Visual Basic 6.0. It will first ask you what kind of project you want:
Choose "Standard EXE" if you are just starting; the result will look something like this:
Move your mouse slowly over the array of icons on the left side; each one raises a "tool tip" that tells what kind of object it is. Select "CommandButton" by pressing it, then move the mouse to the area labeled "Form1". The cursor will change to a large plus sign. Press your mouse button and sweep out a rectangle, then let go. The result will be like this:
You have just created a button whose name is Command1 that also has the caption Command1. You can move the button around or resize it if you're not happy with it. The size and position are properties that you can define and change at will. You can also change the name (we won't bother here) and the caption, which we will do.
Now type the word Quit and the caption on the button will change; notice that the entry for Caption in the Properties window near the right side is highlighted and changes at the same time as you type. You can use either to change the caption.
Now double-click the button (now labeled Quit). A new window will open up, called Project1 - Form1 (Code), and within it will be two lines of text:
This is an example of a code template, for a subroutine called Command1_Click that will be executed when the button Command1 is pressed or clicked. You just have to fill in the action that is to be performed. Type the wordPrivate Sub Command1_Click() End Sub
Finally, the moment of truth. Near the middle of the toolbar at the top of the VB window, there is a small right-pointing blue triangle that will start your program. (The tool tip will say Start.) Press it, and you should see a window labeled Form1 with your Quit button in it:
It's pretty boring, but that is your program running (though it's mostly just waiting for you to press the button). Press the Quit button. That causes the event Command1_Click to occur, which calls your subroutine, which executes the statement End, which stops your program. So the window will go away, and you'll be back in VB.
(You can also stop your program by pressing the small blue square on the VB toolbar, near the Start triangle; this will prove useful if some other more complicated program doesn't work the way you expected. Try it to be sure.)
There's a lot more to it than this, of course, but mostly it's just endless elaboration on what you just did.
Before you can use a variable in a Visual Basic program, you should first declare its type with the Dim statement. For example:
Dim age as Integer, height as Integer Dim first_name as String, last_name as String Dim GPA as Double
You can actually get by without declaring some variables, and VB will do its best to infer what you meant, but it's wiser to declare everything so that VB can check your program more carefully. If you add the line
Option Explicitto the beginning of your code, that will require you to include Dim statements for all variables. This option can also be set via Tools / Options / Editor / Require Variable Declaration; experienced VB programmers always set this option. Even though this makes slightly more work for the programmer, it greatly reduces the chance of a disastrous error that may be hard to find.
Operator | Description |
Assigns value on right to variable on left (e.g. next_year = year + 1) | |
Arithmetic: add, subtract, multiply, divide (integer) | |
Strings: append right string to end of left string | |
Comparators: less than, less than or equals, greater than, greater than or equals | |
More comparators: equals, doesn't equal | |
Conditional AND (true if left and right expressions are both true) and conditional OR (true if either left or right expression is true) |
If condition Then action Else other_action End If
If the condition is true, then the action is taken, otherwise the other_action is taken. The action>s stand for one or more statements. The Else part is optional; sometimes the logic doesn't require it. There is also an ElseIf clause that you can use multiple times to describe a sequence of decisions:
The End If is always necessary.If temperature > 212 Then print "boiling" ElseIf temperature < 0 Then print "freezing" Else print "in between" End If
Do While condition action Loop
As long as the condition is true, then the action will be repeated. There is almost always a While condition attached to the beginning of a Do, to terminate the loop, but it can also appear at the end, or as Until if that reads more naturally.
So, for example, we might print a temperature conversion table like this:
Dim celsius as Double, fahrenheit as Double fahrenheit = 0 Do While fahrenheit <= 212 celsius = 5 / 9 * (fahrenheit - 32) print fahrenheit, celsius fahrenheit = fahrenheit + 1 Loop
For variable = start_value To end_value action Next variable
This performs the action with the variable set in turn to start_value, start_value+1, up to end_value inclusive. This loop will print the same temperature values as the one above:
For fahrenheit = 0 to 212 celsius = 5 / 9 * (fahrenheit - 32) print fahrenheit, celsius Next fahrenheit
It would be called as, for instance,Sub print_ftoc(low As Integer, high As Integer) Dim fahrenheit As Double, celsius As Double For fahrenheit = low to high celsius = 5 / 9 * (fahrenheit - 32) print fahrenheit, celsius Next fahrenheit End Sub
print_ftoc(0, 212)
A function is similar to a subroutine, except that it computes a value that can be used in an expression; mathematical functions like square root (which is called sqr in VB) are good examples.
Both subroutines and functions are usually defined with parameters, so that they can operate on different data values. Here's a function ftoc that converts temperatures from Fahrenheit to Celsius that could have been used in the examples above:
This says that the function is named ftoc; it has an input parameter of type Double that will be referred to as fahrenheit within the function, and it returns a value of type Double.Function ftoc (fahrenheit As Double) As Double ftoc = 5 / 9 * (fahrenheit - 32) End Function
The other output statement that you will use regularly, especially when you're experimenting with your program, is MsgBox, which displays a dialog box. The simplest version is just
which displays a dialog box with the message and an OK button. As a more elaborate example, this code:MsgBox "The end of the world is at hand."
creates this dialog box:Private Sub Disaster_dlg() Dim response As Integer response = MsgBox("Disaster! Give up?", _ vbYesNoCancel + vbQuestion) If response = vbYes Then End ElseIf response = vbNo Or response = vbCancel Then ' do some recovery End If End Sub
There is also a handy function called InputBox that pops up a dialog box with a prompt and a place for you to enter a value. The value is returned as a string; if the user hits the Cancel button, the string is empty (that is, "").
Dim s As String s = InputBox("Enter some text") If s = "" Then Print "You didn't enter anything" Else Print "You entered " & s End If
and to store that same caption in a variable,But1.Caption = "Quit!"
We will see much more of this in the next section.Dim cap as String cap = But1.Caption
Once the interface is designed and in place, the program looks complete: menus will drop down when you click on them, buttons will look pressed when you press them. The only thing wrong is that nothing happens when you press a button, or when you select a menu item. The button knows what to look like when you press it, but you never told it what to do when you press it. To assign actions to the various features of an interface, the program needs to interpret a set of automatically generated messages called events.
When you click on a button, the button generates an event, then sends the event to a routine called the event handler. In VB, events are handled by a subroutine whose name is a combination of the object that detected the event (like Command1) and the specific event type (like Click); thus the name will be, as we saw above, Command1_Click.
The event can be such things as "mouse passed over me", "someone pressed me", or "someone changed the text inside of me". For example, when you click a button But in a window, an event is generated that calls But_Click. Your task is to write statements that do the proper thing when such events are generated.
VB provides a large set of graphical components, of which we will use only a handful: Button, which we have already seen; Label for text display; and TextBox for displaying and reading text. In addition, the Form that contains the other objects is itself an object with properties, methods, and events, and we will manipulate those as well.
When you draw an object like a TextBox on a Form, VB displays a window listing the properties of that object and their current values; here is the Properties window for the original Form itself:
The Name comes first, and the others are listed alphabetically. Note especially the Caption, which is the title of the window, the Back(ground)color, the Font, and (not shown here) the ToolTipText. Almost all properties can be changed when the program is being created, by drawing on the screen or editing the information in the Properties window, or changed when the program is running, by assigning suitable values to the property. For example, you can change the background color to any color you want by
Form1.Backcolor = RGB(100, 150, 200) ' red, green, blue components; each value between 0 and 255
In the next section you will have to create several objects and give them new names. Change the name before you change properties or generate any code because the name is used to identify the object.
Each object responds to a set of events; you can determine what these are by double-clicking on the object to raise a code window, then pull down the list of events at the top right:
Each of these will give you a template for the corresponding subroutine so you can easily write the code to be executed when the event occurs.
You will also notice that VB will raise a menu of legitimate properties as you type, narrowing the list as you type more of the word. If you see the one you want, you can select it with the mouse or hit Tab and VB will complete the typing for you. This popup menu is often very helpful for reminding you of available properties.
Your assignment is to implement a program that will play the old guessing game "I'm thinking of a number between 1 and 100. What is it?". Our version looks like this:
You can make yours look much more professional if you wish, once you have it working properly, by laying out the components anywhere and using any sizes, fonts, and colors that you like.
Your program should do the following:
You must use these names for components so the lab assistants can help you and so we can grade.
Using the icons in the toolbox area on the left side of the VB window, draw the 7 components above on the Form called Form1. As you draw each one, immediately change its name to the corresponding name given above by editing the Name field in the Properties window on the right side of the VB window.
Change the Caption fields of the three Labels to "I'm thinking of a number between 1 and", "What's your guess?", and nothing. Change the captions on the two buttons.
Change the Text property of the range Textbox to 100, and of the guess Textbox to nothing.
Finally, change the Caption property of Form1 to something that includes your name.
You can also print files if you like to keep a paper trail.
Program statements are placed in the Code window, which is often hiding behind the Form window. You can switch back and forth between Code and Form using the entries under the View menu item. You can also freely edit anything in the Code window, especially to delete unwanted items and blank lines. Your entire program is there, though you may have to scroll up and down to see it.
You will need a variable to hold the secret random number that the user is to guess. Since this value will be needed by at least two subroutines of your program, it must be declared at the beginning of your program, before any of the Sub definitions. Go to the code window and type this line:
Dim secretnumber As Integer
Now you can start to add some functionality. First, make the Quit button work. Go to the Code window and select quit from the drop-down list at the top left; this will create a template for subroutine quit_Click. Type in the VB statement that causes the program to terminate. Test the program so far.
secretnumber = Int(rnd * range) + 1The built-in function Rnd produces a different (pseudo-)random number between 0 and 1 each time it is called. The rest of this line converts the characters in the range Textbox into an integer value, then scales up the random number to a random integer between 1 and the range value.
Add a MsgBox statement after this line to display the secret number, then test this part of the program.
Rnd by itself produces a sequence of apparently random numbers, but from a given starting point it's always the same sequence. To get a different sequence (randomized from the time of day), add the line
Randomizebefore the secretnumber = rnd... line. Then the game will be different every time you play it. (Do not add this line until you are sure your program is working; it's easier to debug the program if it behaves the same way each time it runs.)
We have provided a function that causes the guess TextBox to call a subroutine checkguess when the user presses the Enter key:
Copy this and paste it into your VB code window, right after a line that says End Sub.Private Sub guess_KeyDown(KeyCode As Integer, Shift As Integer) If KeyCode = 13 Then ' 13 is the ASCII decimal value for newline checkguess ' you have to write this subroutine... End If End Sub
You have to write the checkguess subroutine, which checks the guess to see if it is correct. To start writing this function, just type Sub checkguess in the code window after an End Sub line; when you push Enter, a new subroutine template will appear and you can insert your code into it.
The user's guess is in the Textbox guess. Add this line as the first line of subroutine checkguess:
userguess = CInt(guess)This will store the user's guess in the variable userguess.
Before you do anything else, verify that you can properly read the user's guess by using a MsgBox to display userguess.
Now you can go on to the real logic of the program: is the user's guess too high, too low, or just right? Your task now is to fill in the last few lines of checkguess to do this test and display the right message as the Caption of the result Label. This will require some If statements that compare the guess to the secret number; look back at the discussion of control flow if you need to.
To set the caption, you will need lines like this one:
result.caption = CStr(userguess) & " is too high"CStr is another built-in VB function that produces a sequence of characters from a numeric value, and the & appends one sequence of characters to the end of another. You will need these here to get neat-looking output.
The very last step of checkguess is to clear the guess textbox so it's ready to accept the next guess. You can do this by assigning a string of no characters to it; that's written as "" (two adjacent double-quote characters).
Since this is your first Visual Basic program you are liable to make mistakes. This is not as bad as it sounds -- if you are methodical, finding these mistakes (or debugging) will not be too hard. A good idea is to write small sections at a time, and test as you go; this is what we have been suggesting above. This approaches makes it much easier to find what section of your code has the error.
Use MsgBox statements to display results as your computation proceeds, or just to verify that your program is going where you think it is. These are easy to add and help narrow down problems quickly.
Another tip for this problem is to display the correct answer right away, until you know the program is working. It's hard to debug a program that generates a different random value each time it runs!
Inside your program text values must appear inside quotes (e.g., "What's your guess?"), The & sign is used to attach two text strings to form a new one (e.g., "Hi " & "There" is the same as "Hi There").
Putting all these together, if you want your MsgBoxes to display both numbers and characters, you will need to use statements like this:
MsgBox "The user's guess is " & CStr(userguess)
You will next be offered the chance to save the VB project itself in Project1.vbp.
Both of these are ordinary text files that you can look at and even change
with Notepad.
It is a very good idea to check with one of the lab assistants
to make sure that they have seen your project in its working state,
that your files have been properly saved in your Unix account, and
that you are sending the right files for grading. Mail the files to yourself
as well and be sure that they have arrived safely.
Do all of these before you log out.
If you've completed the lab, sent your email to cs109@princeton.edu
or cs111@princeton.edu and transferred your work to your Unix account,
then you are finished.
Submitting your work by email