<<

Table of Contents

Introduction ...... -3-

Computer Languages ...... -4-

Problem Solving Strategies ...... -7-

The Liberty Basic Environment ...... -11-

Liberty Basic Commands ...... -13-

Variables and Constants ...... -19-

Mathematical Operators ...... -23-

Error Checking and Debugging ...... -27-

Manipulating Strings ...... -31-

Mathematical Functions ...... -32-

Decision Statements ...... -37-

Iteration ...... -44-

Structured Programming ...... -47-

Graphic User Interface (GUI) ...... -49-

Graphics ...... -64- Preface

This guide was produced to introduce students to the Liberty Basic . The topics of and graphics introduce concepts related to “Windows” object oriented programming. These topics were included so students might experience the transition from code-based programming to the object oriented environment of that is used in the CMP 621 course.

The Teacher's Guide and Lab Manual for Liberty Basic were created by Lianne Garland during the summer of 2006. The Department appreciates the and work that has gone into the creation of these manuals and would like to thank Ms. Garland for her efforts.

We are interested in the ongoing development of these materials. Any comments, suggestions or further exercises would be welcome. Efforts will be made to share these content suggestions and support materials through an online workspace. Please contact the Senior High Technology Specialist at (902) 368-5725 with your suggestions or ideas. Liberty Basic Beginning Computer Programming

Introduction Computer technology is all around us: ATM machines, fuel injection in cars, digital cameras, and telephone communications as well as our personal computers. It is important to know that none of this technology would be possible without computer programming. Programming provides instructions that tell the machine how to operate. Whether it is playing video games or typing a document, the computer requires a set of instructions in order to accomplish the task that you would like it to perform.

Hardware and Software Recall that all of the physical components of a computer make up the hardware and may include your printer, monitor, and other peripheral device. It is easiest to think of of the word “hardware” as describing those parts of a computer that can be touched.

Programs represent software. Recall that there are two main types of software: application software and system software. Application software refer to a set of programs that make a real life task easier to do, like word processors. System software helps the computer deal with the operations, like opening, closing, saving and printing files, as well as communicating with other peripheral devices. System software includes the .

A computer program tells the computer how to accept some of data (input), manipulate that data (process and/or store), and spit it back out again (output). They can be thousands, even hundred thousands of single line commands. Each command doing a small task that the computer obeys.

Input and output for various programs

Type of program Input What the program does Output

Word Processor Characters typed from Formats the text, corrects Displays and prints keyboard spelling neatly organized text

Game Keystrokes or joystick Calculates how fast and moves a cartoon Figure movements how far to a cartoon on screen figure on screen

Web browser HTML codes stored On Converts the HTML codes Displays web pages on other computers into text and graphics the computer screen

If you want your computer to do something specific, you can purchase a software package that will do this for you, or you could write your very own program which tells the computer what to do, step by step.

3 Liberty Basic Beginning Computer Programming

Computer Languages Languages are used in everyday life for communication. In order to communicate effectively, you need to have an understanding of the language in order to convey to others your needs and wants.

Computer languages are similar to spoken languages in that you must use them very precisely so that you are not misunderstood. Computers don’t English (or French, etc), so a set of step by step instructions must be written using a language that the computer can understand, called a programming language. Each language has its own grammar and spelling or syntax which must be followed for the computer to understand that language.

Consider these examples from spoken languages: English: Hello, how are you? French: Bonjour! Ça va bien? German: Guten Tag. Wie geht’s? Japanese: Konnichi wa. O genki desu ka?

All these examples mean the same thing: Each sentence has a greeting followed by a question asking how you are. But each example is a completely different group of words. Unless you know these languages, you may not know that each means the same thing.

Computer languages are similar in that there are basic tasks which any computer language must do for a . The programmer just has to learn to “speak” the language. One advantage of a computer language over a spoken language is that is does not take that long to become fluent in a computer language! Many learn several languages during their careers.

Now read these examples from some computer languages: QBasic if ( x > 5) then: “greater” Pascal if x > 5 then writeln (‘greater’) ++ if ( x > 5) cout << “greater” Java if (x > 5) System.out.println (“greater.”)

All these statements accomplish the same task: If the contents in the variable called “x” is greater than the number “5,” then we will print the word “greater” on the computer screen.

4 Liberty Basic Beginning Computer Programming

Programming Languages

Pascal, , C++, BASIC, ...each language serves a specific purpose.

There are two levels of language among programming languages: high level languages and low level languages.

Low Level Programming Languages Low level programming languages are those that are closest to what the computer understands.

In reality, computers talk in a language that has 2 words: 0 and 1. It's called a binary system. Other than ten, the most common number-system base is two. In fact, the base- two (or binary) system, which consists of nothing but 0's and 1's, is the foundation of every computer's CPU.

Assembly language was developed by programmers so programming would be easier. It uses short, easy to remember phrases such as JMP, MOV, and ADD, which represent specific machine language instructions. Computers can’t read , so it must be translated into machine language using assemblers.

High Level Programming Languages High level languages, such as FORTRAN, COBOL, BASIC and Pascal, were developed because writing machine language or assembly language programs was difficult and confusing.

Programming languages were made to look like ordinary human language in hopes that it would be easier to write programs and make modifications.

5 Liberty Basic Beginning Computer Programming

Translating the code

Translators break down high level and low level language code into machine language understood by the particular processor in the C.P.U. There are two kinds of translators: interpreters and compilers.

When translating any language, human or computer, into another language, one of two methods is generally used.

1. The complete file is translated at one time and then read later. This means that the original needs only to be translated once and then the translated version can be used as often as necessary. This is known as compiling and a compiler is used.

2. The file is translated one line at a time, and is used as it is translated. This means that the original is translated every time that it is used. This is known as interpreting, and an interpreter is used.

Rapid Application Development (RAD) programming languages

Most programming languages were designed back in the days when a computer screen displayed nothing but text. No graphics, mouse pointers, buttons or windows.

When computers developed Graphical User Interfaces (GUI) with windows, scroll bars, and toolbars, people began demanding programs that included all these GUI features as well. To programmers create programs with GUI features, many companies developed special dialects of existing languages, dubbed rapid application development (RAD) languages.

RAD languages enable programmers to design the way they want their program to look and then write to make that user interface actually do something useful, such as display information in a window.

Three popular RAD languages are Visual Basic (derived from BASIC), (based on Pascal), and C++ Builder (based on C++). Liberty Basic can use this feature as well.

6 Liberty Basic Beginning Computer Programming

Programming is Problem Solving

A program tells the computer how to solve a specific problem. A program can be as short as a single instruction or it can contain thousands of instructions. The bigger the problem, the bigger the program. To solve a big problem, you must first tell the computer how to solve a bunch of little problems.

An algorithm is a set of steps for solving a problem. These steps may repeat and may involve some decisions such as a of two or more things.

Consider the following example of an algorithm for buying a ticket to a movie:

1. Go to the movie theatre. 2. Select a movie. 3.Walk to the ticket counter. 4. Pay the price. 5. Receive the ticket.

What about an algorithm for finding the smallest number among three numbers?

1. Compare the first number with the second number. 2. Discard the bigger number from step 1. 3. Compare the third number with the number that is left from step 2. 4. Discard the bigger number from step 3. 5. Whatever number is left is the smallest of all three.

Time

When writing a program, or solving any problem, one of the most important things to remember is that all problems should be broken down into simpler tasks. The hardest part about programming is identifying all the little problems that make up the big problem that is to be solved. Don’t think of the large task, but break down the large task into smaller tasks that can be managed.

Computers need to know EVERYTHING. Unless everything is specified that the computer is to do and exactly how to do it, the computer will not do what it is supposed to do.

7 Liberty Basic Beginning Computer Programming

Much planning goes into writing a program, unless the program is very short and simple. Good programmers spend very little time working at the computer, but a great deal of time working out solutions with pencil and paper.

Writing good, working programs will involve writing many drafts of the program.

Steps to writing a computer program:

1. Defining the problem and determining the expected outcome.

2. Create the program: Make a flowchart or define an algorithm to solve the problem. Determine a list of variables and constants that may be needed for your code. Design the interface and write the code.

3. Input the code and save the program.

4. Run the program.

5. Fix errors. Save the modifications.

6. Go back to step 4.

Basic History

In the early days of small computers, each machine had it’s own version of BASIC (Beginner’s All-Purpose Symbolic Instruction Code). There was no software available, so the user wrote the programs.

The original Basic was created in 1963/64. Later, other versions such as BASICA and GWBASIC followed. In the mid 1980's, QuickBASIC introduced procedural language in which you divide a program into small tasks or modules.

QuickBASIC led to QBasic. QBasic understands the older versions’ language and provides features from other popular computer languages. Visual Basic, which allows you to create Window’s type programs, is based on QBasic programming. Liberty Basic was developed in 1991 by Carl Gundel and is being used as a Windows replacement for QBasic.

8 Liberty Basic Beginning Computer Programming

Flowcharts

Flowcharts are a graphical representation of the steps needed to solve a programming problem. A flowchart will show the logical flow of a solution.

Terminal symbol Used to represent the beginning or the end of a program. There will only be one directional symbol either going out of or into the terminal symbol. Input/Output Used to represent getting information from symbol the user and giving the information back to the user. There will be one directional symbol into and one directional symbol out of an input/output symbol. Process symbol Used to represent calculations or other processing steps. There will be one directional symbol into and one directional symbol out of a process symbol.

Decision symbol Used to represent a comparison. The action taken next depends on the result of the comparison. There will be one directional symbol into and two directional symbol out of a decision symbol. The directional symbols coming out will represent a yes/true and a no/false option. Directional Used to show the flow of information. symbols Information can only travel one way.

Connector Used to represent a break in the code where a symbols loop could be placed.

Flowcharts are part of the planning of programs.

9 Liberty Basic Beginning Computer Programming

Using flowcharts

All programs begin and end, thus all flowcharts begin with a terminal symbol and end with a terminal symbol.

Consider the following problem: You wish to write a program that will average numbers that are inputted by a user. When the user is finished entering numbers, the average will be displayed.

A flowchart for this program would look like this:

10 Liberty Basic Beginning Computer Programming The Liberty Basic Environment

Loading Liberty Basic

Find the Liberty Basic icon on the desktop (in the student group), double click on this. The Liberty Basic editor appears with the Welcome.bas program in it. Open a new file to retrieve a blank editing environment.

The Bar The title bar includes the name and the version of the Liberty Basic program you are using. As well, it indicates the name of the file that you are working on. If you have not saved the file, it will default to Untitled.bas.

11 Liberty Basic Beginning Computer Programming

The Menu Bar The menu bar is located at the top of the screen. The menu bar contains lists of pull down menus to manage Liberty Basic programs.

Menu Contents File New, Open, Insert File Save, Save As, Print, contains all file-related commands with which you can load and save Liberty Basic applications.

Edit Undo, Cut, , Paste, Clear, Select All, Restore, /, Find Again Run Run, , Lite Debug, Kill BASIC programs enables you to execute programs, halt and resume the execution Setup Preferences, Editor Font, Printer Font, Help Index, Tutorials, About

The Toolbar Located directly under the menu bar, the toolbar allows for quick access to commonly used controls in Liberty Basic.

The Reference Bar Located at the bottom of the screen, the reference bar provides quick information about your file.

12 Liberty Basic Beginning Computer Programming Code - Programming

The Liberty Basic language deals with keywords. Keywords have specific meaning in Liberty Basic.

The PRINT Statement

Print is a Liberty Basic keyword for placing output on the screen.

Example: Print “I wish I could take a nap!”

A First Program Type the above “Print” line exactly as it appears in the Editor Window. If there are any typing errors in the line, they must be corrected prior to continuing. Press Enter. This is a complete (although short) Liberty Basic program. Note: Any text that appears in a program in quotation marks is considered to be a string literal.

Keywords like print will be converted to blue text so they can be distinguished from other text.

Running the program

Choose the Run menu, then Run (or Press Shift-F5). The Main window Screen will appear with “I wish I could take a nap!” at the top of the screen. You must close this window (Use the red x in the top right corner of the window. If you do not close it, there will be one window for each time you run the program and this can be confusing).

Add more “Print” lines to the program. Notice that a new Main window opens each time you run the program. It is important to close the execution windows so as you do not have too many windows open at once, causing confusion.

13 Liberty Basic Beginning Computer Programming

The and END Statements

CLS is a Liberty Basic keyword which clears the Main window. Nothing will be left on the window when this command is not followed by any other output commands.

End is a Liberty Basic keyword used to show the logical end of a program. Programmers use this to indicate the end of a program. It is not necessary, however, it is a very acceptable practice. Every program has an end.

Insert the CLS command on a line of it’s own before the PRINT statements and the END statement on a line of it’s own at the end of the program.

Example: CLS Print “ I wish I could take a nap!” ... END

Run the program now (Shift-F5). What is different from the previous program?

Now insert CLS at the bottom of your program before the END statement. Run the program. What is the difference now?

Editing

Use Delete and Backspace to erase characters. Cut, Copy, and Paste can be used like they are in a word processor. Information can be inserted anywhere by just typing. Other characters will move to the right.

Syntax Error Message

A syntax error usually occurs when a command has been misspelled and the message will show up on the Reference Bar. Correct the error and run the program again.

14 Liberty Basic Beginning Computer Programming

Saving From the File menu select Save. Type the name of your file. Liberty Basic will automatically put the bas extension on the file.

Filenames Names should describe what the program involves. Combinations of letters, numbers, and some punctuation marks can be used in file names. Spaces or the following characters: * = + [ ] ; : “ ? < > / \ | cannot be used. The extension of the filename should always be .bas

Save the program that is in the Editor Window as first. Liberty Basic will put the .bas extension on the filename.

If changes are made to a program, it is not possible in Liberty Basic to work on another program until the current program is saved.

Remember to save often.

Starting a New Program From the File menu select New.

Opening an Existing File Choose the Open command from the File menu. Select the file that is to be opened.

Quitting Liberty Basic Choose Exit from the File menu. Save the current program, if need be.

At this point you should have a program called first.bas saved to your g:drive

If you have not done this already, create a folder for your programming files called programs. In this folder, create another folder called labs and one called assigns. Save all of your programs in the appropriate folders.

15 Liberty Basic Beginning Computer Programming

Separators and Zones

A Print statement with nothing else on it prints a blank line.

Example: CLS PRINT “This is the first line” PRINT PRINT “This is the third line”

The Comma Separator A comma is used to separate items in Print statements. It causes the output to be printed across the screen in zones (14 spaces long).

Example: PRINT “Liberty” , “Basic” , “zone 3” , “zone 4”

Commas can be used by themselves to jump to new zones.

Example: PRINT , , , “I’m over here”

Numbers can just be displayed on the Main window, and do not require to be a string literal.

Example: PRINT “a” , “b” , “c” PRINT 1, 2, 3 PRINT -4, -5, -6

The Semicolon Separator A semi-colon prints the next value immediately after the one it just printed out.

Example: PRINT “This” ; “is” ; “pretty” ; “close” PRINT 1; 2; 3; 4 PRINT -1; -2; -3; -4

16 Liberty Basic Beginning Computer Programming

To space words, put blank spaces inside the quotes at the beginning or end of a string.

Example: PRINT “This “ ; “is “ ; “not “ ; “so “ ; “close “

End of a Line : When a comma or semicolon is typed at the end of a Print statement, it causes the output of the next Print statement to be on the same line (if there is room).

Example: PRINT “5 4 3 2 1 0 ” ; PRINT “Blast off !!”

The LOCATE Statement The Locate statement places the cursor at a specific position on the mainwin. Subsequent Print statements display information at the selected position.

LOCATE column, row

Example: LOCATE 13, 20 PRINT “Hello” LOCATE 16, 40 PRINT “Goodbye”

Putting 2 statements on a line.

A colon ( : ) can be used to put several statements on a line.

Example: LOCATE 10, 25 : PRINT “I am the greatest!”

Setting the Main Window size The Mainwin statement sets the number of columns and rows in the main window. This statement should be placed at the top of your program code, below the opening comments.

Syntax: MAINWIN x y Where x represents the number of columns and y represents the number of rows.

17 Liberty Basic Beginning Computer Programming

Documenting the program Remarks, or comments are used to keep track of what a program does. Comments are preceded by the REM statement or ‘ symbol. The comments appear in the program listing, but not in the output. The REM statement can only be used on a separate line of code. Using ‘ for comments will allow comments to be placed on the same line as any code.

Documentation at the top should include: The programmer’s name The date the program was written and last modified What the program is supposed to do How the program works Where the program gets, saves, and outputs data Any known problems with the program

Other remarks may include instructions or reminders as the program goes along.

** All programs that you pass in should include this at the top.

Example:

REM BUSINESS CARD ‘This simple program creates a business card on the screen using string literals ‘Spacing exactly is essential for proper placement of characters ‘For CMP 521 July, 2006

Mainwin 60 30 LOCATE 15, 11 : PRINT “~~~~~~~~~~~~~~~~~~~~~~~~” LOCATE 15, 12 : PRINT “| |” LOCATE 15, 13 : PRINT “| Your Name Here |” LOCATE 15, 14 : PRINT “| Future Programmer |” LOCATE 15, 15 : PRINT “| Novice Computer User |” LOCATE 15, 16 : PRINT “|~~~~~~~~~~~~~~~~~~~~~~~ |” END

Save this program as Card.bas.

18 Liberty Basic Beginning Computer Programming

Variables and Constants

Variables are the most important part of programming. They allow for data to be stored and manipulated so that the computer can react to different types of information and conditions. In Liberty Basic, variables are used to store data in the computer’s memory for as long as the program runs.

Variables have two uses: 1. to store inputted data, 2. to store calculations that use inputted data or previous calculations. Variables are internal labels that the user of the program does not see.

A variable is a letter or a word that is used to represent something that can change. Variable names should be descriptive. The two characteristics of variables are: Every variable has a name; Every variable can hold only one kind of data.

Defining Variables To define a variable means to create and name the variable. Programs can have as many variables as they need to have. Before using a variable, a request must be made for Liberty Basic create the variable by defining the variable first.

When defining a variable, Liberty Basic needs to know 1. The name of the variable. 2. The data type of the variable

Naming Conventions Q Names can be as short as one character or as long as 40 characters. Q Names must begin with a letter of the alphabet (upper or lower case). Q Names can contain letters, numbers or underscores, as well as periods. Names cannot contain other punctuations or blank spaces however. Q Names cannot be the same as keywords (specific command words for coding). Q Names should make sense. Q Names should consist of a three letter prefix that designates the type of variable followed by a unique text description. This, although not necessary is very helpful when determining throughout the program what type of data the variable is holding. Q Names are case sensitive, thus Name, name and NAME are all different in Liberty Basic.

19 Liberty Basic Beginning Computer Programming

The types of Variables Liberty Basic is limited to two types of variables, numbers or strings. For our purposes, we will talk about 3 types of variables: strings, integers and decimals.

Strings Usually letters. If they are numbers, no Prefix: str calculations can be preformed on them. 0 to 32767 characters

Integers whole numbers and their opposites Prefix: int

Single - Precision decimal numbers Prefix: sng decimal numbers

At the end of any string variable, Liberty Basic needs to have the $ symbol, otherwise it will treat this variable as though it were a number.

Declaring Variables All variables should be declared at the beginning of a program. This will identify all variable names used in the program. This will help in understanding what the program does. Also, by defining what type of data the variable will hold, errors that may occur if your variable was to hold the wrong type of data will be avoided.

Liberty Basic does not require the declaration of a variable prior to using it, but for the sake of good programming, and practice, we will declare all variables at the beginning of our programs in comments.

The DIM statement DIM (short for dimension) statements are used to define variables.

The declaration statement always has the following form: DIM variablename As datatype

To declare a variable for a place of birth. Variable name: birthplace Data Type: string The declaration statement would be Example: ‘DIM strBirthPlace$ As String

20 Liberty Basic Beginning Computer Programming

Initial values All numeric data types are initialized to 0 (zero). String variables are initialized to an empty string (“ ”). Thus, if a variable name is mistyped, a program may return a value that does not make sense for what the program should do. Remember to be very vigilant with spellings and typing of variables and constants.

Constants A constant is a data value that does not change.

To use constants in Liberty Basic we just assign a value to it. To avoid confusion, constants that are being used in programs should be listed below the variables in the commented section at the beginning of the program.

Example: ‘Const sngPi = 3.14 ‘This line defines the constant for Pi

sngPi = 3.14 ‘ This line assigns 3.14 to the constant

The advantages to using constants in a program are to identify numeric or string values with descriptive names and, if the constant value is used often in a program, changing the value is easier if the value only needs to be changed once. For instance, to change GST from 7% to 6% would be easy in a program where the constants were indicated at the beginning, and the number 0.07 was not used throughout the program.

21 Liberty Basic Beginning Computer Programming

Handling Input and Output

Most programs accept information from the user, manipulate that information and present new (or maybe the same) information to the user.

Input happens when a program accepts information from the user.

The Input Statement A program, in order to be interactive, must be able to accept data from the user.

Input is the keyword for getting information from the user. Variables are used to temporarily store the information being accepted.

Example:

‘ For CMP 521, July, 2006 ‘ This program tells a story of wishful thinking. ‘ The user inputs two names when prompted and the program displays a short story

‘ ***Variables used *** ‘ DIM strTeacher$ As String

CLS

PRINT “What is the name of your teacher?” INPUT strTeacher$ ‘ this variable holds the name of a teacher. PRINT strTeacher$+ “ is a wonderful human being. Didn’t they just win the lottery?” PRINT “What is the your name?” INPUT strTeacher$ ‘This variable now holds the user’s name. PRINT strTeacher$ + “, looks like you’re the teacher now.”

END

Save this program as Dreaming.bas.

When this program is RUN in Liberty Basic, notice that the Main window will display the text What is the name of your teacher? ?

This second line is prompting us to enter a name, thus placing information in the variable (which had been empty). The program then writes the inputted name together with the string literal provided in the code. Note that the + symbol is used to combine string literals and variables.

22 Liberty Basic Beginning Computer Programming

The second input statement in this program uses the same variable, thus when we run the program, the information that was stored in the variable in the beginning is actually replaced by what we enter the second time.

Manipulating Data

All programs should have the ability to process data and return useful information to the user.

Mathematical Operators

Operators are mathematical operations. Operators are as follows: exponents - ^ division - / multiplication - * integer division - \ modulus - MOD (Determines the remainder) addition - + subtraction - - brackets - ( & )

Expressions are mathematical statements. Because we are dealing with numbers, we do not need to put the statements in quotation marks. Expressions follow order of operations (BEDMAS).

Assignment Statements

Assignment statements will store values in main memory in the location of the variable or constant. They can be used to assign values directly to variables or constants or to assign the result of a calculation to a numeric variable.

23 Liberty Basic Beginning Computer Programming

Example: ‘ For CMP 521, July, 2006 ‘ This program calculates and displays a pay based on $7 per hour for 40 hours. ‘ There is no input for this program.

‘** variables and constants ‘DIM intPay As Integer ‘Const intHours = 40 ‘Const sngRate = 7

‘**constant assignment intHours = 40 sngRate = 7

‘** calculation and display intPay = intHours * sngRate Print intPay

END

Save this program as Pay.bas.

Solving a problem using all steps

Step 1. Defining the problem and determining the expected outcome.

Example: Write a program that will perform addition, subtraction, multiplication, and division on two numbers that are entered by a user. The result of the operation will be displayed.

24 Liberty Basic Beginning Computer Programming

Step 2. Create the program: Make a flowchart or define an algorithm to solve the problem.

Flowchart:

25 Liberty Basic Beginning Computer Programming

The Code REM This program performs various mathematical operations on two integers. REM The user inputs the integers. REM The output is the result, as well as the operation performed. REM For CMP 521, July, 2006

REM Define variables ‘DIM intFirstNumber As Integer, intSecondNumber As Integer ‘DIM sngResult As Single

REM Get integers from user. PRINT “Enter the first integer.” INPUT intFirstNumber PRINT “Enter the second integer.” INPUT intSecondNumber

REM Calculations

REM Addition sngResult = intFirstNumber + intSecondNumber Print "Addition of "; intFirstNumber; " and "; intSecondNumber; " is "; sngResult Print

REM Subtration sngResult = intFirstNumber - intSecondNumber Print “Subtraction of “ ; intSecondNumber ; “ from“ ; intFirstNumber ; “ is “; sngResult Print

REM Multiplication sngResult = intFirstNumber * intSecondNumber Print “Product of “ ; intFirstNumber ; “ and “ ; intSecondNumber ; “ is “; sngResult Print

REM Division sngResult = intFirstNumber / intSecondNumber Print “Division of “ ; intFirstNumber ; “ by “ ; intSecondNumber ; “ is “; sngResult Print

END

Step 3. Input the code and save the program. Save this program as math.bas

Step 4. Run the program.

Step 5. Fix errors. Save the modifications.

26 Liberty Basic Beginning Computer Programming

Checking for errors

Liberty Basic allows for two types of error checking: Compiler Reporting and the Debugger.

Compiler Reporting The compiler has a mechanism that will report any interesting things that are found when Liberty Basic is compiling a program. For example, if two variable names are the same, with the exception of their capitalization, the reporter will find this.

For instance, in the above program, if an error was made in typing IntFirstNumber and IntFirstnumber was typed instead, the compiler reporting pane wold appear at the

bottom of the Liberty Basic editor.

The compiler reporter will also indicate variable names that have similar names, for instance name$ and names$. Ensure that variable names are descriptive and meaningful.

27 Liberty Basic Beginning Computer Programming

The Debugger If a program does not behave the way that it is expected to behave, the debugger can be used to watch each line of the code as it is executed. Once code has been typed into the editor for a program, and the program has been saved, clicking the debug button in the toolbar will cause the debugger window to open, as well as a window to execute the code (similar to the main window). Positioning both

windows so that they can be viewed makes debugging easier.

Notice that the top pane of the debugger window lists the program’s variables. All of the numeric variables are initialized to zero.

28 Liberty Basic Beginning Computer Programming

The toolbar of the debugger window contains the buttons for possible debugging modes.

Resume runs the program at full speed.

Stop will cause the program to stop and highlights the code in the debugger window where it stopped. It also shows the current variable contents at the point of the stop.

Step into executes the next line of code. If the next line of code is a or a function, it will follow the execution into these.

Step over executes the next line of code. If the next line of code is a subroutine or a function, it will not follow the execution into these.

Step out will run until the current subroutine or function exits, and then stops to show the next line of code and variables.

Animate runs your program, showing each line as it executes and updates the variables as it runs.

29 Liberty Basic Beginning Computer Programming

By using the step into button, Liberty Basic allows for reading of the program one line at a time. The execution window will run the program and allow for input and output of

the program as it would if you were to run the program in the main window.

Inputting values in the execution window will change the values of the variables in the debugging window.

Using the Debug feature will help ensure where problems with the execution of a program are taking place and allow for corrections more quickly.

30 Liberty Basic Beginning Computer Programming

Manipulating Strings

Remember that a string is anything that appears in quotation marks.

Concatenating Strings The process of combining two strings is called concatenating. To do this, use the plus sign (+) to combine the information. We used this in the dreaming.bas program.

The process of combining strings with numbers, also concatenating, must be done using the semi-colon (;). We used this in the math.bas program.

Uppercase and Lowercase functions Strings which contain letters appear in three ways. - all lowercase - all uppercase - a mixture of uppercase and lowercase.

Lower$ is the function used to a string to all lowercase letters. Example: Print Lower$ (“HELLO!”)

Upper$ is the function used to convert a string to all uppercase letters. Example: Print Upper$ (“What’s Up?”)

Note: Without the Print statements, the Functions Lower$ and Upper$ will display nothing.

Other character manipulation functions:

LEN( string ) is the function used to return the length in characters of string.

31 Liberty Basic Beginning Computer Programming

Mathematical Functions

Liberty Basic allows for many mathematical functions. Functions are subprograms that calculate and return a single value to a program. The following is a list of functions and what their purpose is.

ABS (n) This function returns the absolute value of n. Example: Print ABS (-7) Print ABS (4)

SQR (n) This function returns the square root of the number n. Recall that the square root of a negative value is not possible. Example: Print SQR (81) Print SQR (0)

EXP (n) This function returns en. (e = 2.7182818...) Example: Print EXP (5)

LOG (n) This function returns the natural log (ln) of n. (It is important to note that this is not the base 10 log like a scientific calculator, but the base e log or ln.) Example: Print LOG (7)

INT (n) This function will remove any decimals attached to a number, leaving only the whole number. It is useful when the program calls for integers and users enter decimals. Example: Print “Enter an integer:” Input intNumber intNumber = INT (intNumber) ‘ run this entering a decimal number Print intNumber

32 Liberty Basic Beginning Computer Programming

Formatting Numbers Sometimes it is useful to display numeric values with a limited number of decimal points, like when displaying the price of something. In order to accomplish this, the program must be told how to the numeric value. This can be accomplished with the Using ( ) statement. Syntax: USING (templateString, numericExpression) Here the templateString consists of the character # to indicate placement for numerals and a dot (.) To indicate placement for the decimal point. The #’s must be placed in double quotation marks. If there are more digits in the numericExpression than allowed for in the templateString, the digits will be dropped or truncated (no rounding).

The numericExpression can be a numeric variable, or a number.

The Using statement must be assigned to a string literal variable or used with the Print statement. Having the code on its own does not give any noticeable results.

Example: ‘Calculating the cost of a 2.99 item. ‘For computer 521, July, 2006

‘** variables and constants declared ‘DIM sngPST as Single ‘DIM sngGST as Single ‘DIM sngSubtotal as Single ‘DIM sngTotal as Single ‘Const sngItem = 2.99 ‘Const sngPST = 0.10 ‘Const sngGST = 0.06

‘** constant assignment sngItem = 2.99 sngPST = 0.10 sngGST = 0.06

‘** calculations according to PEI taxes sngGST = sngItem * sngGST sngSubtotal = sngItem + sngGST sngPST = sngSubtotal * sngPST sngTotal = sngSubtotal + sngPST

Print “Your total is $ ” + USING (“###.##”, sngTotal) END Save the program as PEItax.bas.

33 Liberty Basic Beginning Computer Programming

Thus far, all programs have been small, but as programs become larger, it is necessary to plan appropriately for the journey. Planning ahead can save from frustration later.

The following is a sample program with all steps included.

Step 1. Defining the problem and determining the expected outcome.

This program will produce a short story about the user’s favourite actors.

Step 2. Create the program: Make a flowchart or define an algorithm to solve the problem.

34 Liberty Basic Beginning Computer Programming

Determine a list of variables and constants that may be needed for your code. strUsername$ - for the user’s name strTown$ - for the town of the user strActor1$ - one of the user’s favourite actors strActor2$ - another of the user’s favourite actors

Design the interface and write the code.

REM This program will ask the user questions and output a short story. REM For CMP 521, July, 2006

REM Declare variables ‘DIM strUserName$ AS String ‘DIM strTown$ AS String ‘DIM strActor1$ AS String ‘DIM strActor2$ AS String

REM Get information from user Print “What is your name?” Input strUserName$ Print “Where do you live?” Input strTown$ Print “Who is your favourite actor?” Input strActor1$ Print “Who is your favourite actress?” Input strActor2$

CLS

REM Tell the story Print “ Once upon a time, in a small part of the world known as “ + strTown$ + “a wonderful” Print “ thing happened.” Print strActor1$ + “ was spotted buying ice cream for “ + strActor2$ + “.” Print “( “ + strActor2$ + “ was waiting in a silver BMW).” Print Print “Although people from “+ strTown$ + “ were surprised to see “+ strActor1$ +“ and “ Print strActor2$ + “, they were not shocked that they would visit such a wonderful place.” Print Print “And so, “ + strUserName$ + “, this is where the story ends, without spreading rumours.”

END

35 Liberty Basic Beginning Computer Programming

Step 3. Input the code and save the program.

To be done on the computer (try the above program and save it as story.bas)

Step 4. Run the program.

Step 5. Fix errors. Save the modifications.

Syntax errors can be difficult to find sometimes. Check for spacing, and misspellings first (especially in variables). The compiler and the debug features of Liberty Basic will help you with this part.

Step 6. Go back to step 4.

Repeat until the program is complete.

Step 7. Documentation.

Code alone can be difficult to follow for those who did not write the program. Keep this in mind and document your programs.

Don’t forget to save.

36 Liberty Basic Beginning Computer Programming

Decisions

The answer “maybe” never occurs in programming. The answer to a question is always “yes” or “no”, “true” or “false”, or something else which is specific. This, in computer terms is a Boolean expression, that is it represents a true or false value. You establish “questions” by placing conditional expressions in your programs. Liberty Basic evaluates these to determine whether they are true or false. In order to ask questions that have a yes or no answer, we need to have comparison tools, or relational operators.

Relational Operators

= equal <> not equal > greater than >= greater than and equal < less than <= less than and equal

Conditional Statements

The IF-THEN statement The If - Then statement allows Liberty Basic to make decisions based on conditions. If the condition is true, the statement is executed. If the condition is false, Liberty Basic ignores the statement and moves to the next line.

Syntax: IF condition THEN ‘Series of statements END IF

37 Liberty Basic Beginning Computer Programming

Example:

‘ This program asks the user a mathematical problem and requests an answer. ‘ a message is displayed accordingly. ‘ For Computer 521, July, 2006

‘** variables declared ‘DIM intAnswer AS Integer

CLS Print “What is 13 * 4" INPUT intAnswer ‘ allows the user to input an answer IF intAnswer = 52 THEN ‘ checks to see if the user input the correct answer PRINT “Correct !” ‘ this statement is only executed if the user is correct END IF ‘ ends the conditional statement IF intAnswer <> 52 THEN PRINT “Wrong ! The correct answer is 52.” END IF ‘ ends the conditional statement END

Save the program as IfThen.bas.

The above program prompts the user to determine the value of 13 x 4. The value that the user enters is stored in the variable intAnswer. It is compared to the value 52 and if this is the value entered by the user, the user receives a Correct response, if not, any other numeric value will return an incorrect response.

The IF - THEN - ELSE statement

The ELSE keyword allows for a double-alternative decision. One action is taken if the condition is true; another action is taken if the condition is false.

Syntax: IF condition THEN ‘Series of statements ELSE ‘Series of statements END IF

38 Liberty Basic Beginning Computer Programming

Example: ‘ This program asks the user a mathematical problem and requests an answer. ‘ a message is displayed accordingly. It uses the Else keyword. ‘ For Computer 521, July, 2006

‘** variables declared ‘DIM intAnswer AS Integer

Print “What is 13 * 4" INPUT intAnswer ‘ allows the user to input an answer

IF intAnswer = 52 THEN ‘ checks to see if the user input the correct answer PRINT “Correct !” ‘ this statement is only executed if the user is correct ELSE ‘ executes if the user is not correct PRINT “Wrong ! The correct answer is 52.” END IF ‘ ends the conditional statement

END

Save the program as Else.bas.

Notes : 1. Indent any statements inside the conditional so the program is easy to read. 2. You can put as many statements in the blocks as you want. 3. ELSE and END IF must be on lines of their own. 4. Use blank spaces between main parts of the program for greater readability.

39 Liberty Basic Beginning Computer Programming

Longer Conditional Statements

If there are more than two conditional statements, If-then statements can be nested.

Example: ‘ This program asks the user when UPEI opened. A message is displayed accordingly. ‘ It uses nested if-then statements. ‘ For Computer 521, July, 2006

‘** variables declared ‘DIM intYear AS Integer

PRINT “Welcome to UPEI Trivia !”

PRINT “In what year was the University of Prince Edward Island opened?” INPUT intYear

IF intYear = 1969 THEN PRINT “That’s right !” PRINT “You’re quite a historian.” ELSE IF intYear < 1969 THEN PRINT “ Saint Dunstan’s University and Prince of Whales College” PRINT “ were still in operation.” ELSE PRINT “No. You’re incorrect.” PRINT “Why don’t you ask your teacher?” END IF END IF PRINT “Thanks for guessing.”

END

Save the program as Nested.bas.

40 Liberty Basic Beginning Computer Programming

If more than one condition results in a true value, Liberty Basic can compare more than one value using boolean operators.

Boolean Operators

OR Only one of the conditions must be true before the statement can be executed.

Example:

‘This program asks the user to guess a number between one and ten. ‘If the choice made is a four or a nine, then the program declares the user ‘a winner. ‘For CMP 521, July, 2006

‘** variables declared** ‘DIM intGuess AS Integer

PRINT “Guess a number between 1 and 10" INPUT intGuess

IF intGuess = 4 OR intGuess = 9 THEN PRINT “You’re a winner!” ELSE PRINT “You lose!” END IF

PRINT “Thanks for playing.” END

Save the program as Or.bas.

Note: When using strings in conditional statements, everything must be exact. “Cow” is different from “cow” and different from “C O W”.

41 Liberty Basic Beginning Computer Programming

AND Both condition 1 and condition 2 must be true before the statement can be executed.

Example: ‘ This programs wants the user to select both a number and a letter. ‘ If the number one and the letter b, the user is declared lucky. ‘ Any other combination will not result in being lucky. ‘ For CMP 521, July, 2006

‘** variables declared ** ‘DIM intNumber AS Integer ‘DIM strLetter$ AS String

PRINT “Pick a number: 1 or 2" INPUT intNumber PRINT “Pick a letter: a or b” INPUT strLetter$ IF intNumber = 1 AND strLetter$ = “b” THEN PRINT “You’re lucky!” ELSE PRINT “Try again” END IF END

Save the program as And.bas.

NOT If the condition is false, then the statement will be executed.

Example: ‘ This programs wants the user to enter their age. A message is displayed accordingly. ‘ For CMP 521, July, 2006

‘** variables declared ** ‘DIM intAge AS Integer

PRINT “What is your age " INPUT intAge IF NOT intAge > 16 THEN PRINT “You’re a young pup!” ELSE PRINT “You’re getting old” END IF END

42 Liberty Basic Beginning Computer Programming

Save the program as Not.bas.

Select Case If there are many possible conditions that may be met, select case may be a better option than nested If-then statements.

Syntax: Select Case Case condition ‘series of statements Case condition ‘series of statements ... Case Else ‘series of statements End Select

Example: ‘ This program asks the user a math problem and a message is displayed accordingly. ‘ It uses Select case. ‘ For Computer 521, July, 2006

‘** variables declared ‘Dim intResult as Integer

Print “ What is the difference between 10 and 6 ?” Input intResult

Select Case Case (intResult = -4) Print “ Subtract the smaller number from the larger to obtain 4.” Case (intResult = 4 ) Print “ You really know your subtraction facts!” Case ( intResult = 60) Print “ You have found the product, not the difference.” Case Else Print “Maybe you have mistyped the answer.” End Select END

Save the program as Case.bas.

43 Liberty Basic Beginning Computer Programming

LOOPS

Liberty Basic provides three constructions for looping. A loop allows you to repeat one or more statements without repeating the code.

The FOR / NEXT statements execute a loop a specific number of times. The starting and ending value are specified. Variables used as indices for loops are typically not declared, their purpose is only to count.

Syntax: For numeric_variable = to stop ‘Statements Next numeric_variable

Note: most programmers use the Tab key to indent any statements found inside a loop.

Example: FOR i = 1 TO 20 PRINT i , “Jelly Beans are the best !” NEXT i

Example: FOR i = 5 TO 15 PRINT i , NEXT i

Example: FOR j = 2 TO 50 STEP 2 PRINT j ; NEXT j

Example: FOR k = 10 TO 1 STEP -1 PRINT k PRINT “going down ...” NEXT k

Notes: 1. The starting number must be smaller than the ending number unless going backwards. 2. The STEP function allows you to “step” up a certain amount at a time. 3. To go backwards, use STEP followed by a negative number. 4. Any number of statements can be put inside the loop. 5. The loop variable can be any letter or valid variable name. (i, j, and k are common loop variables & variable names are numbers)

44 Liberty Basic Beginning Computer Programming

Exit For If it is necessary to exit a For/Next loop before the counter variable has reached its final value, use the Exit For statement. This will allow the program to exit the loop properly and to preserve the current value of the counter variable.

Example: For x = 1 to 20 y = x*3 If y > 40 then Exit For Next x

Print “final x value ”; x Print “final y value ”; y

The While/Wend statement executes a loop as long as a specified condition evaluates to True.

Syntax: While condition ‘Series of Statements Wend

Example: x = 0 While x < 10 x = x + 1 Print x Wend

The Do loop provides a loop that executes at least once and then only loops back as long as the condition is met.

Do Syntax: Do ‘Series of statements Loop While condition

45 Liberty Basic Beginning Computer Programming

Example: Do Print x x = x + 1 Loop While x > 10

Example: Do Print y y = y + 1 Loop While y < 10

Do Until Loop Syntax: Do ‘Series of statements Loop Until condition

Example: Do Print x x = x + 1 Loop Until x = 1

Example: Do Print y y = y + 1 Loop Until y = 10

46 Liberty Basic Beginning Computer Programming

Structured Programming

The ultimate goal of programming is to write programs that use the least amount of memory while accomplishing as much as possible. As programs become larger (and more complex) organization is the key. Breaking large problems into smaller parts leads naturally into using . Each subroutine should accomplish a major task.

A subroutine acts like a miniature program within your program. Every subroutine consists of: ~a name - should never be a Liberty Basic keyword, like Print ~one or more instructions that you want the subroutine to follow ~any data that you want the subroutine to use

In Liberty Basic, a subroutine is not completely separate from the rest of the program, but the code is placed after the END statement of the program.

Syntax: SUB subroutine_name ‘ instructions for the subroutine END SUB

Any variables listed with a subroutine is called a parameter list.

To create a subroutine in Liberty Basic After the End statement of the program, type the syntax needed for the subroutine.

Global Variables Using variables within a subroutine requires that they be declared globally (able to be used anywhere within the program). To declare variables globally, use the Global statement.

Syntax: Global variable_name The variable data type can be commented at the end of the statement.

Calling a Subroutine A Subroutine must be called to perform the tasks within a program

Syntax: CALL Subroutine_name

47 Liberty Basic Beginning Computer Programming

Example Compare this program with the one found on page 33.

REM This program will ask the user questions and output a short story. REM It uses subroutines to accomplish this. REM For CMP 521, July, 2006

REM Declare variables Global strUserName$ ‘AS String Global strTown$ ‘AS String Global strActor1$ ‘AS String Global strActor2$ ‘AS String Call GetData CLS Call Display END ‘~~~~~~~~~~~~~~~~~~~~~~~~ SUB GetData REM Get information from user Print “What is your name?” Input strUserName$ Print “Where do you live?” Input strTown$ Print “Who is your favourite actor?” Input strActor1$ Print “Who is your favourite actress?” Input strActor2$ END SUB ‘~~~~~~~~~~~~~~~~~~~~~~~~~~ SUB Display REM Tell the story Print “Once upon a time, in a small part of the world known as “+strTown$+ “a ” Print “ wonderful thing happened.” Print strActor1$ + “ was spotted buying ice cream for “ + strActor2$ + “.” Print “( “ + strActor2$ + “ was waiting in a silver BMW).” Print Print “Although people from “ + strTown$ + “ were surprised to see “ + strActor1$ Print “and “+ strActor2$ + “, they were not shocked that they would visit such a Print “wonderful place.” Print Print “And so, “ + strUserName$ + “, this is where the story ends, without spreading” Print “ rumours.” END SUB

Save the program as Sub.bas.

48 Liberty Basic Beginning Computer Programming Graphic User Interfaces (GUI)

The term Graphical User Interface refers to a window and all of its controls. These are the graphical elements that interact with the user of the program. Most programs that are used today are GUIs.

The NOMAINWIN Command The simplest form of the GUI using Liberty Basic can be accomplished using the NOMAINWIN command. In doing this, we eliminate the appearance of the Main window that will display text and ask the user for input. However, if this is used, commands like Print and Input no longer work as they have before.

Displaying output - Notice command The Notice command will create a Notice dialog box and works the same as the Print command.

Example: NOMAINWIN NOTICE “I wish I could take a nap!”

Getting input - Prompt command The Prompt command creates a Prompt dialog box, which will include a textbox for the user to respond in. The Prompt command is followed by a question and a variable. Syntax: PROMPT “prompting question?”; variable

Example: ‘DIM strTeacher$ as String NOMAINWIN PROMPT “What is the name of your teacher?”; strTeacher$ NOTICE strTeacher$+ “ is a wonderful human being.” END

It is important to note that the OK button on the Notice dialog box must be clicked before returning to the code in the Liberty Basic editor.

49 Liberty Basic Beginning Computer Programming

Creating windows

Handles Any window that is created in Liberty Basic must be given a nickname or handle. A window handle must begin with the pound symbol (#). This identifies the window for Liberty Basic.

Open command The Open command opens a window and has the following syntax:

Open “Title” for window as #handle_name

Size and Position of windows Prior to opening a window, Liberty Basic must know the size of the window and the position on the screen (from the upper left corner) that the window will open at.

WindowWidth = a Window Height = b

Both a and b are measured in pixels.

UpperLeftX = x UpperLeftY = y x represents the number of pixels from the left edge of the screen that the window will open and y represents the number of pixels from the top of the screen.

Wait Command This statement causes the program execution to stop and wait for user input events. Program execution will continue when the user interacts with a window or other control owned by the program. Without having this code, a run-time error will occur.

50 Liberty Basic Beginning Computer Programming

Example: ‘This program will open a window sized at 300 by 100 at position 200, 150. ‘The window will have a title “My first window!” ‘Created for Computer 521

‘Setting the size and position of the window WindowWidth = 300 WindowHeight = 100 UpperLeftX = 200 UpperLeftY = 150

‘opening a window Open "My first window!" for window as #myFirst

‘Now stop and wait Wait End

Save the program as FirstWindow.bas.

Trapclose command The trapclose command is used to direct program flow when a user uses the X closing button or the system close button instead of some other form of exiting a window (like a menu item). The program may need to ask for verification that the user wants to close, it may need to close files, write to ini data, or set a flag to indicate that a window is closed. Thus, the close must be trapped. The trapclose command works with all window types.

Syntax: print #handle_name, "trapclose subroutine_name"

This will tell Liberty Basic to use the code at the subroutine as an event handler for the window.

Confirm Command The confirm command will automatically display a yes and a no command button in a prompting dialog box.

Syntax: Confirm “message”; string_variable

51 Liberty Basic Beginning Computer Programming

Example:

‘This program will open a window. ‘If the user closes the program with the X, the program will confirm that it is to close. ‘Created for Computer 521

‘**Variables declared Global strQuit$ ‘Used to store yes or no from the Quit subroutine

‘Setting the size and position of the window WindowWidth = 300 WindowHeight = 100 UpperLeftX = 200 UpperLeftY = 150

‘opening a window Open "My first window!" for window as #myFirst print #myFirst, "trapclose Quit"

‘Now stop and wait Wait End ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub Quit handle$ confirm "Do you want to quit?"; strQuit$ If strQuit$ = "no" Then wait End If close #handle$ END End sub

Save the program as Closing.bas.

52 Liberty Basic Beginning Computer Programming

Adding controls in a window

Controls like command buttons, checkboxes, radio buttons and textboxes can be added to a window. For each control that is added, code must be written to tell the program what to do. This code is referred to as an event and is best coded as a subroutine. The commands to create a controls must specify event handlers that are associated with user actions made on those controls (clicking, double-clicking, selecting, etc.).

Command Buttons Command Buttons can be clicked by the user . When the program is run, and the user clicks on this button, then execution calls the subroutine, passing the handle of the button as an argument to the subroutine.

Syntax:

BUTTON #handle_name.Button_name, “Button text”, subroutine_name, UL, xpos, ypos, width, height

Button - creates a button inside the window with the handle name specified. #handle_name - the nickname for the window. .Button_name - button names should be descriptive, and for good programming, should begin with the prefix cmd. Button Text - is the text, or caption that appears on the button for the user. Subroutine_name - indicates the name of the subroutine that holds the events to take place if the button is clicked UL - indicates that the position of the button is from the upper left. Xpos & Ypos - the number of pixels from the upper left of the window. Width and height - the number of pixels of the button size.

53 Liberty Basic Beginning Computer Programming

Example:

‘This program will open a window with a command button on it. ‘The Ok command button will display a notice box when clicked. ‘Created for Computer 521

‘**Variables Global strQuit$ ‘Used to store yes or no from the Quit subroutine

‘Setting the size and position of the window WindowWidth = 300 WindowHeight = 100 UpperLeftX = 200 UpperLeftY = 150

‘opening a window button #myCommandButton.cmdOk, "OK!", ok, UL, 15, 15 Open "Command Button Example!" for window as #myCommandButton print #myCommandButton, "trapclose Quit"

‘Now stop and wait Wait End ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub Quit handle$ confirm "Do you want to quit?"; strQuit$ If strQuit$ = "no" Then wait End If close #handle$ END End sub ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub OK handle$ Notice “ you clicked the OK button!” Close #handle$ End Sub

Save the program as button.bas.

54 Liberty Basic Beginning Computer Programming

Displaying Text When text is used to display information inside a window, it is known as static text. This text cannot be changed by the user.

Syntax: STATICTEXT #handle_name.TextID , “Static Text”, xpos, ypos, width, height

StaticText - creates the text inside a window. #handle_name - the nickname for the window. .TextID - identifies the Static text and should begin with the prefix sta. Static Text - is the text, or caption that appears on the window for the user. Xpos & Ypos - the number of pixels from the upper left of the window. Width and height - the size of the actual text.

Example: ‘This program will open a window with a command button on it and some text. ‘The Change command button will display new text when clicked. ‘Created for Computer 521

‘**Variables declared Global strQuit$ ‘Used to store yes or no from the Quit subroutine

‘Do not display main window Nomainwin

‘Setting the size and position of the window WindowWidth = 300 WindowHeight = 100 UpperLeftX = 200 UpperLeftY = 150

‘opening a window Statictext #myMain.staTextID, “This is some text!” , 10, 10, 150, 25 Button #myMain.cmdChange, "Change", CHANGE, UL, 25, 35 Open "Static Text Example!" for window as #myMain Print #myMain, "trapclose Quit"

Wait END

‘ ****Subroutines on next page*****

55 Liberty Basic Beginning Computer Programming

Example continued: ‘~~~~~~~~~~~~~~~~~~~~~ Sub CHANGE handle$ Print #myMain.staTextID , "This text is different" WAIT Close #handle$ End Sub

‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub Quit handle$ Confirm "Do you want to quit?"; strQuit$ If strQuit$ = "no" Then wait End If close #handle$ END End sub

Save the program as Text.bas.

Adding Textboxes Textboxes provide a space for a user to type text. They are typically used to collect input from the user.

Syntax: Textbox #handle_name.Textbox_name, xpos, ypos, width, height

Textbox - creates the text box inside a window. #handle_name - the nickname for the window. .textbox_name - identifies the textbox and should begin with the prefix txt. Xpos & Ypos - the number of pixels from the upper left of the window. Width and height - the size of the box.

Inserting text into a textbox To insert text into a textbox you need to use the PRINT command and identify the window handle, the textbox name and the text you want to insert.

Syntax: Print #handle_name.textbox_name, “message”

56 Liberty Basic Beginning Computer Programming

Retrieving text from a textbox

To retrieve text from a textbox and assign the text to a string variable, use the Print and the Input commands.

Syntax: Print #handle_name.textbox_name, “ !contents? ” Input #handle_name.textbox_name, string_variable$

Using the above code, the 1st line will retrieve the contents of the textbox and the 2nd line assigns the text to a string variable.

Example:

‘This program will give the user a choice of buttons for clearing a textbox or displaying ‘the contents of the textbox in a Notice dialog box ‘Created for Computer 521

‘**Variables Global strQuit$ ‘Used to store yes or no from the Quit subroutine Global strUserInput$ ‘Used to store user input from the textbox

‘Do not display main window Nomainwin

‘Setting the size and position of the window WindowWidth = 300 WindowHeight = 250 UpperLeftX = 200 UpperLeftY = 150

‘opening a window Textbox #myMain.txtUserInput, 25, 25, 150, 50 Button #myMain.cmdClear, "Clear", CLEAR, UL, 30, 125, 40, 40 Button #myMain.cmdDisplay, "Display", DISPLAY, UL, 80, 125, 40, 40 Open "TextBox Example!" for window as #myMain Print #myMain, "trapclose Quit"

Wait END

‘ ****Subroutines on next page*****

57 Liberty Basic Beginning Computer Programming

Example continued: ‘~~~~~~~~~~~~~~~~~~~~~ Sub CLEAR handle$ Print #myMain.txtUserInput, “ ” WAIT Close #handle$ End Sub

‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub DISPLAY handle$ Print #myMain.txtUserInput, "!contents?" Input #myMain.txtUserInput, strUserInput$ Notice strUserInput$ Wait Close #handle$ End Sub ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub Quit handle$ Confirm "Do you want to quit?"; strQuit$ If strQuit$ = "no" Then wait End If close #handle$ END End sub

Save the program as Textbox.bas.

Creating Checkboxes Checkboxes provide the user several options to choose from and more than one check box can be selected at one time. A checkbox displays a box for the user to click and also a caption to describe the option.

Syntax: CHECKBOX #handle_name.CheckBox_name, “Caption”, setEvent, resetEvent, xpos, ypos, width, height

CHECKBOX - creates the Checkbox inside a window. #handle_name - the nickname for the window. .Checkbox_name - identifies the Checkbox and should begin with the prefix chk. Caption - defines the text to be displayed next to the checkbox. setEvent - defines instructions to follow if user selects checkbox. resetEvent - defines instructions to follow if user clears checkbox. Xpos & Ypos - the number of pixels from the upper left of the window. Width and height - the size of the box.

58 Liberty Basic Beginning Computer Programming

Checkbox Commands

Selecting the checkbox This will make a checkmark appear within a checkbox. Print #handle_name.CheckBox_name, "set"

Clearing the Checkbox This will make any checks in the checkbox disappear. Print #handle_name.CheckBox_name, "reset"

Determining if a checkbox is checked This will set a string variable to the value of “set” for checked and “reset” for unchecked. Print #handle_name.CheckBox_name, "value? Stringvariable_name$"

Example: ‘This program will give the user a choice of checkboxes for displaying ‘the grade they are in. Once unselected, they will be prompted to select a grade ‘Created for Computer 521

‘**Variables Global strQuit$ ‘Used to store yes or no from the Quit subroutine

‘Do not display main window Nomainwin

‘Setting the size and position of the window WindowWidth = 300 WindowHeight = 250 UpperLeftX = 200 UpperLeftY = 150

‘opening a window Checkbox #myMain.chkGrade10,”Grade 10", Grade10Set, Grade10Reset 25, 25, 80, 30 Checkbox #myMain.chkGrade11, “Grade 11", Grade11Set, Grade11Reset 25, 55, 80, 30 Checkbox #myMain.chkGrade12, “Grade 12", Grade12Set, Grade12Reset 25, 85, 80, 30

Open "CheckBox Example!" for window as #myMain Print #myMain, "trapclose Quit"

Wait END

‘ ****Subroutines on next page*****

59 Liberty Basic Beginning Computer Programming

Example continued: ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub Grade10Set handle$ Notice “You are in grade 10!” WAIT Close #handle$ End Sub ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub Grade10Reset handle$ Notice “Please select a Grade.” Wait Close #handle$ End Sub ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub Grade11Set handle$ Notice “You are in grade 11!” WAIT Close #handle$ End Sub ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub Grade11Reset handle$ Notice “Please select a Grade.” Wait Close #handle$ End Sub ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub Grade12Set handle$ Notice “You are in grade 12!” WAIT Close #handle$ End Sub ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub Grade12Reset handle$ Notice “Please select a Grade.” Wait Close #handle$ End Sub ‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub Quit handle$ Confirm "Do you want to quit?"; strQuit$ If strQuit$ = "no" Then wait End If close #handle$ END End sub Save the program as Check.bas.

60 Liberty Basic Beginning Computer Programming

Creating Radio Buttons Radio buttons allow the user to select only one option at a time, unlike checkboxes which allow the user to select several options at the same time. A radio button displays a button for the user to click and also a caption to describe the option.

Syntax: RadioButton #handle_name.RadioButton_name, “Caption”, setEvent, resetEvent, xpos, ypos, width, height RadioButton - creates the RadioButton inside a window. #handle_name - the nickname for the window. .RadioButton_name- identifies the RadioButton and should begin with the prefix opt. Caption - defines the text to be displayed next to the radiobutton. setEvent - defines instructions to follow if user selects radiobutton. resetEvent - defines instructions to follow if user clears radiobutton. Xpos & Ypos - the number of pixels from the upper left of the window. Width and height - the size of the box.

RadioButton Commands

Selecting the RadioButton This will make a dot appear within the radio Button. Print #handle_name.RadioButton_name, "set"

Clearing the RadioButton This will make any dots in the radio button disappear. Print #handle_name.RadioButton_name, "reset"

Determining if a RadioButton is selected This will set a string variable to the value of “set” for selected and “reset” for unselected. Print #handle_name.RadioButton_name, "value? Stringvariable_name$"

Creating Group Boxes A group box simply surrounds a group of controls such as checkboxes or radiobuttons. Group boxes frame the options and group them together and are especially useful when a GUI contains more than one group of check boxes or radio buttons.

Syntax: GROUPBOX #handle_name.GroupBox_name, “Caption”, xpos, ypos, width, height

61 Liberty Basic Beginning Computer Programming

GroupBox - creates the GroupBox or frame inside a window. #handle_name - the nickname for the window. .GroupBox_name - identifies the GroupBox and should begin with the prefix fra. Caption - defines the text to be displayed at the top of the GroupBox. Xpos & Ypos - the number of pixels from the upper left of the window. Width and height - the size of the box.

Groupbox commands must be placed prior to the radiobuttons or checkboxes that must be grouped together.

Example: ‘This program will give the user a choice of radiobuttons in a frame to select their age. ‘Created for Computer 521

Global strQuit$ 'Used to store yes or no from the Quit subroutine Global strAgeSelected$ ‘Used to store the value of the radiobutton

' Do not display main window Nomainwin

' Setting the size and position of the window WindowWidth = 300 WindowHeight = 250 UpperLeftX = 200 UpperLeftY = 150

' opening a window Groupbox #myMain.fraAgeCategory, "Select your Age", 15, 10, 110, 110 Radiobutton #myMain.optUnder16, "Under 16",OptionSet, OptionReset 25, 25, 80, 30 Radiobutton #myMain.opt16or17, "16 or 17",OptionSet, OptionReset 25, 55, 80, 30 Radiobutton #myMain.optOver17, "Over 17", OptionSet, OptionReset 25, 85, 80, 30

Open "RadioButton and Groupbox Example!" for window as #myMain Print #myMain, "trapclose Quit"

Wait END

‘** subroutines continued on next page.

62 Liberty Basic Beginning Computer Programming

Example continued: ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub OptionSet handle$ ' This subroutine assigns the value of the radiobuttons to the variable ' strAgeSelected$ and notifies the user of their age with a Notice dialog box.

Print #myMain.optUnder16, "value? strAgeSelected$" If strAgeSelected$ = "set" Then Notice "You are really young for Grade 11." End If Print #myMain.opt16or17, "value? strAgeSelected$" If strAgeSelected$ = "set" Then Notice "You are right on track for your age." End If Print #myMain.optOver17, "value? strAgeSelected$" If strAgeSelected$ = "set" Then Notice "You are a young adult." End If wait close #handle$ End sub

' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub OptionReset handle$ wait close #handle$ End sub

' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub Quit handle$ Confirm "Do you want to quit?"; strQuit$ If strQuit$ = "no" Then wait End If close #handle$ END End sub

Save the program as Radio.bas.

63 Liberty Basic Beginning Computer Programming Graphics

Graphics and sound naturally make programs more interesting. Although Liberty Basic cannot display graphics to the extent that the monitors of today are capable of, there are commands for drawing lines, circles and points, as well as choosing different colours.

Creating a graphics window

In order to create and display graphics, a graphics control must be created. To do this, a graphics window is created. The difference between a window and a graphics window is that the latter will display graphics. It is not advisable to place controls (see GUI section) within a graphics window as they may not work as would be expected.

Syntax: Open “title” for graphics as #handle_name

Setting the colour of the background The window’s colour can be set to a predetermined colour or an RGB value.

Syntax: Print #handle_name, “fill predetermined_colour”

Predetermined colours must be from the following list: black, blue, brown, buttonface, cyan, darkblue, darkcyan, dark gray, dark-green, darking, darked, green, light gray, pellagra, pink, red, white, yellow.

OR Print #handle_name, “fill red_value green_value blue_value”

The red_value, green_value and blue_value specifies a number between 0 and 255 to indicate the RGB colour. This will only work with display modes greater than 256 colours. RGB values can be determined using a graphics program such as PaintShop Pro, or Paint..

Example: Nomainwin Open “Nice Background colour” for Graphics as #myDrawing Print #myDrawing, “fill 214 51 15" wait

64 Liberty Basic Beginning Computer Programming

Notice that in the above example, the horizontal and vertical scroll bars are enabled. Even if the program had specified a size, the scroll bars would still be there. In order to deactivate the ability to scroll, the horizscrollbar and vertscrollbar statements must be set to the off value.

Scroll Bar Statements

Syntax: Print #handle_name, “horizscrollbar on/off” Print #handle_name, “vertscrollbar on/off” Only one of the on or off options are included in the code.

Flush Statement The Flush statement ensures that once grahics are drawn that they “stick”. It may be the case that code will do nothing unless you make it stick to the window.

Syntax: Print #handle_name, “flush”

Example:

Nomainwin Open “No scroll bars” for Graphics as #myDrawing Print #myDrawing, “fill pink" Print #myDrawing, “flush” Print #myDrawing, “horizscrollbar off” Print #myDrawing, “vertscrollbar off” wait

Drawing For the program to draw lines, circles or points Turtle Graphics are used. The program tells the turtle (or robotic pen) to put down the pen and move in directions coded to draw. When drawing is complete, the program must tell the turtle to lift the pen.

Setting the pen down to draw In order for any drawing in the window to occur, the pen must be set down on the window.

Syntax: Print #handle_name, “down”

65 Liberty Basic Beginning Computer Programming

Setting the size of the Pen The default size for the pen is one (1) pixel. The size of the pen can be increased for any subsequent statements used after this code.

Syntax: Print #handle_name, “Size S” S represents the size in pixels of the pen.

Setting the Pen colour The Pen’s colour can be set to a predetermined shade or any RGB value.

Syntax: Print #handle_name, “color predetermined_colour”

OR Print #handle_name, “color red_value green_value blue_value”

(Recall that most programs are “American”, thus the keywords will have US spellings, not Canadian: ie. color)

The SET Statement The SET keyword is used to draw a single point using the current pen colour and size.

Syntax: Print #handle_name, “SET x, y” X represents the row of the pixel and y represents the column of the pixel.

66 Liberty Basic Beginning Computer Programming

Example: ‘ This program will display dots on a yellow background ‘ For computer 521

‘** Variables declared Global strQuit$

' Do not display main window Nomainwin

' Setting the size and position of the window WindowWidth = 150 WindowHeight = 100 UpperLeftX = 200 UpperLeftY = 200

' Opening a graphics window Open "My dots" for Graphics as #myDrawing Print #myDrawing, "trapclose Quit" Print #myDrawing, "fill yellow" Print #myDrawing, "flush" Print #myDrawing, "horizscrollbar off" Print #myDrawing, "vertscrollbar off"

‘ Drawing the dots Print #myDrawing, "down" ' one black dot Print #myDrawing, "set 20, 15" ' A white dot of pixel size 5 Print #myDrawing, "size 5" Print #myDrawing, "color white" Print #myDrawing, "set 30, 15" ' A dark gray dot of pixel size 10 Print #myDrawing, "size 10" Print #myDrawing, "color darkgray" Print #myDrawing, "set 30, 40"

Wait End ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sub Quit handle$ Confirm "Do you want to quit?"; strQuit$ If strQuit$ = "no" Then wait End If close #handle$ END End sub Save the program as Spots.bas.

67 Liberty Basic Beginning Computer Programming

The LINE Statement The Line keyword is used to draw a straight line from one coordinate to another.

Syntax: Print #handle_name, “Line X1 Y1 X2 Y2" X1 and Y1 represent the starting coordinate of the line and X2 and Y2 represent the ending coordinate of the line.

Example: Nomainwin Open "A Line" for Graphics as #myDrawing Print #myDrawing, "fill cyan" Print #myDrawing, "flush" Print #myDrawing, "horizscrollbar off" Print #myDrawing, "vertscrollbar off"

‘ place the pen down Print #myDrawing, “down”

‘ Draw a line, width 7 Print #myDrawing, “size 7" Print #myDrawing, “Line 10 25 250 25"

wait

The Place statement The place statement can be used to reposition the pen without drawing any graphics. Syntax: Print #handle_name, “place X Y” The pen will be positioned at the x, y coordinate.

The Backcolor statement This command is used to set the colour of a drawn figure (box, circle, ellipse, or pie). The code must be placed before the figure and on its own will not result in any changes for the user.

Syntax: Print #handle_name, “backcolor predetermined_colour” OR Print #handle_name, “backcolor red_value green_value blue_value”

68 Liberty Basic Beginning Computer Programming

The Box statement The Box statement will draw a box using the pen position as one corner and coordinates specified as the opposite corner.

Syntax: Print #handle_name, “box x y” x, y are the coordinates for the box drawing to stop.

Example: Nomainwin Open "An open rectangle" for Graphics as #myDrawing Print #myDrawing, "fill 12 22 131" Print #myDrawing, "flush" Print #myDrawing, "horizscrollbar off" Print #myDrawing, "vertscrollbar off"

‘ place the pen down Print #myDrawing, “down”

‘ Draw a white rectangle Print #myDrawing, “color white" Print #myDrawing, “place 10 20" Print #myDrawing, “box 250 200"

wait

To draw a box that has a different colour from the window background, the Boxfilled statement is used. The box will be filled with the colour specified using the Backcolor statement.

Syntax: Print #handle_name, “boxfilled x y” x, y are the coordinates for the box drawing to stop.

69 Liberty Basic Beginning Computer Programming

Example: Nomainwin Open "A filled rectangle" for Graphics as #myDrawing Print #myDrawing, "fill 12 22 131" Print #myDrawing, "flush" Print #myDrawing, "horizscrollbar off" Print #myDrawing, "vertscrollbar off"

‘ place the pen down Print #myDrawing, “down”

‘ Draw a red rectangle that is pink inside Print #myDrawing, “size 4" Print #myDrawing, “color red" Print #myDrawing, “backcolor pink” Print #myDrawing, “place 10 20" Print #myDrawing, “boxfilled 250 200"

wait

The CIRCLE Statement The Circle keyword is used to draw circles on the window. Like boxes, circles can be open or they can be filled with a backcolor. The pen must be placed at center of the circle.

Syntax: Print #handle_name, “circle ” r represents the radius of the circle.

Example:

Nomainwin Open "An open circle" for Graphics as #myCircle Print #myCircle, "fill brown" Print #myCircle, "flush" Print #myCircle, "horizscrollbar off" Print #myCircle, "vertscrollbar off"

‘ place the pen down Print #myCircle, “down”

‘ **continued on next page

70 Liberty Basic Beginning Computer Programming

Example continued: ‘ Draw an orange circle Print #myCircle, “size 2" Print #myCircle, “color 242 120 22" Print #myCircle, “place 100 100" Print #myCircle, “circle 50"

wait

To draw a circle that is filled with a different colour from the window background, the Circlefilled statement is used. The circlewill be filled with the color specified using the Backcolor statement.

Syntax: Print #handle_name, “circlefilled r” r represents the radius of the circle.

Example:

Nomainwin Open "A filled circle" for Graphics as #myCircle Print #myCircle, "fill cyan" Print #myCircle, "flush" Print #myCircle, "horizscrollbar off" Print #myCircle, "vertscrollbar off"

‘ place the pen down Print #myCircle, “down”

‘ Draw an orange circle Print #myCircle, “size 12" Print #myCircle, “color lightgray" Print #myCircle, “backcolor darkgray” Print #myCircle, “place 75 150" Print #myCircle, “circlefilled 50"

wait

71 Liberty Basic Beginning Computer Programming

The Ellipse Statement This command will draw an ellipse in the window with a specified width and height. Again, placing the pen prior to drawing is important.

Syntax: Print #handle_name, “ellipse w h” w and h represent the width and the height in pixels of the ellipse. or for a filled ellipse Print #handle_name, “ellipsefilled w h”

Example:

Nomainwin Open "Two ellipses" for Graphics as #myEllipse Print #myEllipse, "fill 127 0 127" Print #myEllipse, "flush" Print #myEllipse, "horizscrollbar off" Print #myEllipse, "vertscrollbar off"

‘ place the pen down Print #myEllipse, “down”

‘ Draw an open ellipse Print #myEllipse, "size 6" Print #myEllipse, "color pink" Print #myEllipse, "place 40 20" Print #myEllipse, "ellipse 45 20"

‘ Draw a filled ellipse Print #myEllipse, “size 1" Print #myEllipse, “color white" Print #myEllipse, “backcolor darkgray” Print #myEllipse, “place 75 150" Print #myEllipse, “ellipsefilled 10 90"

wait

72 Liberty Basic Beginning Computer Programming

The Pie Statement This command will draw a pie slice inside an ellipse of a specified width and height. The start and stop angles for the pie must be specified as well. If the second angle is positive, the pie will sweep clockwise. If the second angle is negative, the pie will sweep counter-clockwise. Angles are expressed in degrees, and remember there are 360° in a complete revolution. Using small angle sizes will result in a triangular shape

Syntax: Print #handle_name, “pie w h start_angle stop_angle” w represents the width of the ellipse and h represents the height of the ellipse. Start_angle and stop_angle represent the angles in for starting and stopping at. OR for filled pies Print #handle_name, “piefilled w h start_angle stop_angle” The fill color of the pie must be set using the Backcolor command’

Displaying text on the Graphics window In order to display text on a graphics window, the font face and size must first be set.

The Font Statement Syntax: Print #handle_name, “Font font_face font_size” font_face is specified by the name of the font. Font names can easily be found in WordPerfect. The entire name of the font must be used, including spaces. If Liberty Basic cannot find the exact font, it will try to match it as close as possible. font_size represents the size of the font.

Adding Text Syntax: Print #handle_name, “\text1\text2” Text1 is displayed at the current pen position. The \ causes a carriage return and line feed and text2 will be displayed under text1. Subsequent lines of text can be added by adding more \.

73 Liberty Basic Beginning Computer Programming

Example:

Nomainwin Open "Pies and text example" for Graphics as #myDraw Print #myDraw, "fill 0 130 0" Print #myDraw, "flush" Print #myDraw, "horizscrollbar off" Print #myDraw, "vertscrollbar off"

‘ place the pen down Print #myDraw, “down”

‘ Draw an open pie Print #myDraw, "size 2" Print #myDraw, "color blue" Print #myDraw, "place 40 20" Print #myDraw, "pie 200 100 0 97"

'Draw a filled pie Print #myDraw, "size 1" Print #myDraw, "color white" Print #myDraw, "backcolor darkgray" Print #myDraw, "place 75 150" Print #myDraw, "piefilled 25 90 180 -90"

' Place some Text Print #myDraw, "place 20 100" Print #myDraw, "color black" Print #myDraw, "backcolor 0 130 0" Print #myDraw, "FONT Comic Sans 17" Print #myDraw, "\Liberty Basic\is FUN!"

wait

Clearing the Graphics window To clear all of the graphics from the window the CLS command can be used. This will remove everything from the window. Syntax: Print #handle_name, “CLS”

74