table of contents - · pdf filepreface this guide was produced to introduce students to the...

74
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-

Upload: truongkhanh

Post on 12-Mar-2018

233 views

Category:

Documents


10 download

TRANSCRIPT

Page 1: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

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-

Page 2: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Preface

This guide was produced to introduce students to the Liberty Basic programming language. Thetopics of graphical user interface and graphics introduce concepts related to “Windows” objectoriented programming. These topics were included so students might experience the transitionfrom code-based programming to the object oriented environment of Visual Basic that is used inthe CMP 621 course.

The Teacher's Guide and Lab Manual for Liberty Basic were created by Lianne Garland duringthe summer of 2006. The Department appreciates the time and work that has gone into thecreation 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 orfurther exercises would be welcome. Efforts will be made to share these content suggestions andsupport materials through an online workspace. Please contact the Senior High TechnologySpecialist at (902) 368-5725 with your suggestions or ideas.

Page 3: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

3

IntroductionComputer technology is all around us: ATM machines, fuel injection in cars, digitalcameras, and telephone communications as well as our personal computers. It isimportant to know that none of this technology would be possible without computerprogramming. 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 ofinstructions in order to accomplish the task that you would like it to perform.

Hardware and SoftwareRecall that all of the physical components of a computer make up the hardware andmay 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 ofprograms that make a real life task easier to do, like word processors. System softwarehelps the computer deal with the basic operations, like opening, closing, saving andprinting files, as well as communicating with other peripheral devices. System softwareincludes the operating system.

A computer program tells the computer how to accept some type of data (input),manipulate that data (process and/or store), and spit it back out again (output). Theycan be thousands, even hundred thousands of single line commands. Each commanddoing 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 fromkeyboard

Formats the text, correctsspelling

Displays and printsneatly organized text

Game Keystrokes or joystickmovements

Calculates how fast andhow far to move a cartoonfigure on screen

moves a cartoon Figureon screen

Web browser HTML codes stored Onother computers

Converts the HTML codesinto text and graphics

Displays web pages onthe computer screen

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

Page 4: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

4

Computer LanguagesLanguages are used in everyday life for communication. In order to communicateeffectively, you need to have an understanding of the language in order to convey toothers your needs and wants.

Computer languages are similar to spoken languages in that you must use them veryprecisely so that you are not misunderstood. Computers don’t understand English (orFrench, etc), so a set of step by step instructions must be written using a language thatthe computer can understand, called a programming language. Each language has itsown grammar and spelling or syntax which must be followed for the computer tounderstand 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 aquestion 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 computerlanguage must do for a programmer. The programmer just has to learn to “speak” thelanguage. One advantage of a computer language over a spoken language is that is doesnot take that long to become fluent in a computer language! Many programmers learnseveral languages during their careers.

Now read these examples from some computer languages:QBasic if ( x > 5) then: print “greater”Pascal if x > 5 then writeln (‘greater’)C++ 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 computerscreen.

Page 5: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

5

Programming Languages

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

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

Low Level Programming LanguagesLow level programming languages are those that are closest to what the computerunderstands. In reality, computers talk in a language that has 2 words: 0 and 1. It's called a binarysystem. 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 ofevery computer's CPU.

Assembly language was developed by programmers so programming would be easier. Ituses short, easy to remember phrases such as JMP, MOV, and ADD, which representspecific machine language instructions. Computers can’t read assembly language, so itmust be translated into machine language using assemblers.

High Level Programming LanguagesHigh level languages, such as FORTRAN, COBOL, BASIC and Pascal, were developedbecause writing machine language or assembly language programs was difficult andconfusing.

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

Page 6: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

6

Translating the code

Translators break down high level and low level language code into machine languageunderstood 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 twomethods 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 translatedversion can be used as often as necessary. This is known as compiling anda compiler is used.

2. The file is translated one line at a time, and is used as it is translated. Thismeans that the original is translated every time that it is used. This isknown 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 screendisplayed 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 aswell. To help programmers create programs with GUI features, many companiesdeveloped special dialects of existing languages, dubbed rapid application development(RAD) languages.

RAD languages enable programmers to design the way they want their program to lookand then write source code 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), Delphi (based onPascal), and C++ Builder (based on C++). Liberty Basic can use this feature as well.

Page 7: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

7

Programming is Problem Solving

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

An algorithm is a set of steps for solving a problem. These steps may repeatand may involve some decisions such as a choice 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 toremember is that all problems should be broken down into simpler tasks. The hardestpart about programming is identifying all the little problems that make up the bigproblem that is to be solved. Don’t think of the large task, but break down the large taskinto smaller tasks that can be managed.

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

Page 8: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

8

Much planning goes into writing a program, unless the program is very short andsimple. Good programmers spend very little time working at the computer, but a greatdeal 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 theproblem.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, sothe user wrote the programs.

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

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

Page 9: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

9

Flowcharts

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

Terminal symbol Used to represent the beginning or the end ofa program. There will only be one directionalsymbol either going out of or into theterminal symbol.

Input/Outputsymbol

Used to represent getting information fromthe user and giving the information back tothe user. There will be one directional symbolinto and one directional symbol out of aninput/output symbol.

Process symbol Used to represent calculations or otherprocessing steps. There will be one directionalsymbol into and one directional symbol out ofa process symbol.

Decision symbol Used to represent a comparison. The actiontaken next depends on the result of thecomparison. There will be one directionalsymbol into and two directional symbol out ofa decision symbol. The directional symbolscoming out will represent a yes/true and ano/false option.

Directionalsymbols

Used to show the flow of information. Information can only travel one way.

Connectorsymbols

Used to represent a break in the code where aloop could be placed.

Flowcharts are part of the planning of programs.

Page 10: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

10

Using flowcharts

All programs begin and end, thus all flowcharts begin with a terminal symbol and endwith 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:

Page 11: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

11

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 fileto retrieve a blank editing environment.

The Title BarThe title bar includes the name and the version of the Liberty Basic program you areusing. As well, it indicates the name of the file that you are working on. If you have notsaved the file, it will default to Untitled.bas.

Page 12: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

12

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

Menu Contents

File New, Open, Insert File Save, Save As, Print, Exitcontains all file-related commands with which you can load and saveLiberty Basic applications.

Edit Undo, Cut, Copy, Paste, Clear, Select All, Restore, Find/Replace, FindAgain

Run Run, Debug, Lite Debug, Kill BASIC programsenables you to execute programs, halt and resume the execution

Setup Preferences, Editor Font, Printer Font,

Help Index, Tutorials, About

The ToolbarLocated directly under the menu bar, the toolbar allows for quick access to commonlyused controls in Liberty Basic.

The Reference BarLocated at the bottom of the screen, the reference bar provides quick information aboutyour file.

Page 13: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

13

Code - Programming

The Liberty Basic language deals with keywords. Keywords have specific meaning inLiberty 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 anytyping errors in the line, they must be corrected prior to continuing. Press Enter. This isa complete (although short) Liberty Basic program. Note: Any text that appears in a program in quotation marks is considered to be a stringliteral.

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

Running the program

Choose the Run menu, then Run(or Press Shift-F5). The Mainwindow Screen will appear with “Iwish I could take a nap!” at the topof the screen. You must close thiswindow (Use the red x in the topright corner of the window. If youdo not close it, there will be onewindow for each time you run theprogram and this can beconfusing).

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

Page 14: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

14

The CLS and END Statements

CLS is a Liberty Basic keyword which clears the Main window. Nothing will be left onthe 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. Programmersuse this to indicate the end of a program. It is not necessary, however, it is a veryacceptable practice. Every program has an end.

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

Example:CLSPrint “ 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 theprogram. 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 theright.

Syntax Error Message

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

Page 15: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

15

SavingFrom the File menu select Save. Type the name of your file. Liberty Basic willautomatically put the bas extension on the file.

FilenamesNames should describe what the program involves. Combinations of letters, numbers, and some punctuation marks can be used in filenames.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 .basextension on the filename.

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

Remember to save often.

Starting a New ProgramFrom the File menu select New.

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

Quitting Liberty BasicChoose 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 calledprograms. In this folder, create another folder called labs and one called assigns. Saveall of your programs in the appropriate folders.

Page 16: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

16

Separators and Zones

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

Example:CLSPRINT “This is the first line”PRINTPRINT “This is the third line”

The Comma SeparatorA comma is used to separate items in Print statements. It causes the output to beprinted 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 stringliteral.

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

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

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

Page 17: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

17

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 StatementThe 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, 20PRINT “Hello”LOCATE 16, 40PRINT “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 sizeThe 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 openingcomments.

Syntax:MAINWIN x y

Where x represents the number of columns and y represents the number of rows.

Page 18: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

18

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

Documentation at the top should include:The programmer’s nameThe date the program was written and last modifiedWhat the program is supposed to doHow the program worksWhere the program gets, saves, and outputs dataAny 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 30LOCATE 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.

Page 19: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

19

Variables and Constants

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

Variables have two uses: 1. to store inputted data, 2. to store calculations that useinputted data or previous calculations. Variables are internal labels that the user of theprogram 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: Everyvariable has a name; Every variable can hold only one kind of data.

Defining VariablesTo 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, arequest must be made for Liberty Basic create the variable by defining the variable first.

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

Naming ConventionsQ 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. Namescannot 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 ofvariable followed by a unique text description. This, although not necessary isvery helpful when determining throughout the program what type of data thevariable is holding.Q Names are case sensitive, thus Name, name and NAME are all different inLiberty Basic.

Page 20: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

20

The types of VariablesLiberty 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: strcalculations can be preformed on them. 0 to 32767 characters

Integers whole numbers and their opposites Prefix: int

Single - Precision decimal numbers Prefix: sngdecimal numbers

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

Declaring VariablesAll variables should be declared at the beginning of a program. This will identify allvariable names used in the program. This will help in understanding what the programdoes. Also, by defining what type of data the variable will hold, errors that may occur ifyour 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 thesake of good programming, and practice, we will declare all variables at the beginning ofour programs in comments.

The DIM statementDIM (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 beExample:

‘DIM strBirthPlace$ As String

Page 21: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

21

Initial valuesAll 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 avalue that does not make sense for what the program should do. Remember to be veryvigilant with spellings and typing of variables and constants.

ConstantsA 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 thecommented 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 valueswith descriptive names and, if the constant value is used often in a program, changingthe value is easier if the value only needs to be changed once. For instance, to changeGST from 7% to 6% would be easy in a program where the constants were indicated atthe beginning, and the number 0.07 was not used throughout the program.

Page 22: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

22

Handling Input and Output

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

Input happens when a program accepts information from the user.

The Input StatementA 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 totemporarily 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 displaythe text

What is the name of your teacher??

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

Page 23: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

23

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

Manipulating Data

All programs should have the ability to process data and return useful information tothe 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 donot need to put the statements in quotation marks. Expressions follow order ofoperations (BEDMAS).

Assignment Statements

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

Page 24: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

24

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 assignmentintHours = 40sngRate = 7

‘** calculation and displayintPay = intHours * sngRatePrint 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 ontwo numbers that are entered by a user. The result of the operation will be displayed.

Page 25: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

25

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

Flowchart:

Page 26: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

26

The CodeREM 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 intFirstNumberPRINT “Enter the second integer.”INPUT intSecondNumber

REM Calculations

REM AdditionsngResult = intFirstNumber + intSecondNumberPrint "Addition of "; intFirstNumber; " and "; intSecondNumber; " is "; sngResultPrint

REM SubtrationsngResult = intFirstNumber - intSecondNumberPrint “Subtraction of “ ; intSecondNumber ; “ from“ ; intFirstNumber ; “ is “; sngResultPrint

REM MultiplicationsngResult = intFirstNumber * intSecondNumberPrint “Product of “ ; intFirstNumber ; “ and “ ; intSecondNumber ; “ is “; sngResultPrint

REM DivisionsngResult = intFirstNumber / intSecondNumberPrint “Division of “ ; intFirstNumber ; “ by “ ; intSecondNumber ; “ is “; sngResultPrint

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.

Page 27: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

27

Checking for errors

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

Compiler ReportingThe compiler has a mechanism that will report any interesting things that are foundwhen Liberty Basic is compiling a program. For example, if two variable names are thesame, 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 andIntFirstnumber 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, forinstance name$ and names$. Ensure that variable names are descriptive andmeaningful.

Page 28: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

28

The DebuggerIf a program does not behave the way that it is expected to behave, the debugger can beused to watch each line of the code as it is executed. Once code has been typed into theeditor for a program, and the program has been saved, clicking the debugbutton in the toolbar will cause the debugger window to open, as well as awindow 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 thenumeric variables are initialized to zero.

Page 29: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

29

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 highlightsthe code in the debugger window where it stopped. It alsoshows the current variable contents at the point of thestop.

Step into executes the next line of code. If the next line of code is a subroutine ora 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 ora function, it will not follow the execution into these.

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

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

Page 30: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

30

By using the step into button, Liberty Basic allows for reading of the program one line ata 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 thedebugging window.

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

Page 31: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

31

Manipulating Strings

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

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

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

Uppercase and Lowercase functionsStrings which contain letters appear in three ways.

- all lowercase- all uppercase- a mixture of uppercase and lowercase.

Lower$ is the function used to convert 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 displaynothing.

Other character manipulation functions:

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

Page 32: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

32

Mathematical Functions

Liberty Basic allows for many mathematical functions. Functions are subprograms thatcalculate and return a single value to a program. The following is a list of functions andwhat 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 anegative 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 notthe 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 wholenumber. It is useful when the program calls for integers and users enter decimals.Example:

Print “Enter an integer:”Input intNumberintNumber = INT (intNumber) ‘ run this entering a decimal numberPrint intNumber

Page 33: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

33

Formatting NumbersSometimes it is useful to display numeric values with a limited number of decimalpoints, like when displaying the price of something. In order to accomplish this, theprogram must be told how to format the numeric value. This can be accomplished withthe Using ( ) statement.Syntax:

USING (templateString, numericExpression)Here the templateString consists of the character # to indicate placement for numeralsand a dot (.) To indicate placement for the decimal point. The #’s must be placed indouble quotation marks. If there are more digits in the numericExpression thanallowed 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 Printstatement. 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 assignmentsngItem = 2.99sngPST = 0.10sngGST = 0.06

‘** calculations according to PEI taxessngGST = sngItem * sngGSTsngSubtotal = sngItem + sngGSTsngPST = sngSubtotal * sngPSTsngTotal = sngSubtotal + sngPST

Print “Your total is $ ” + USING (“###.##”, sngTotal)END

Save the program as PEItax.bas.

Page 34: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

34

Thus far, all programs have been small, but as programs become larger, it is necessary toplan 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.

Page 35: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

35

Determine a list of variables and constants that may be needed for yourcode.

strUsername$ - for the user’s namestrTown$ - for the town of the userstrActor1$ - 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 userPrint “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 storyPrint “ Once upon a time, in a small part of the world known as “ + strTown$ + “awonderful” Print “ thing happened.”Print strActor1$ + “ was spotted buying ice cream for “ + strActor2$ + “.”Print “( “ + strActor2$ + “ was waiting in a silver BMW).”PrintPrint “Although people from “+ strTown$ + “ were surprised to see “+ strActor1$ +“ and “Print strActor2$ + “, they were not shocked that they would visit such a wonderful place.”PrintPrint “And so, “ + strUserName$ + “, this is where the story ends, without spreading rumours.”

END

Page 36: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

36

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 youwith 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 inmind and document your programs.

Don’t forget to save.

Page 37: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

37

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 isa 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 todetermine whether they are true or false. In order to ask questions that have a yes or noanswer, 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 statementThe If - Then statement allows Liberty Basic to make decisions based on conditions. If thecondition is true, the statement is executed. If the condition is false, Liberty Basic ignores thestatement and moves to the next line.

Syntax:IF condition THEN

‘Series of statementsEND IF

Page 38: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

38

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

CLSPrint “What is 13 * 4"INPUT intAnswer ‘ allows the user to input an answerIF intAnswer = 52 THEN ‘ checks to see if the user input the correct answer

PRINT “Correct !” ‘ this statement is only executed if the user is correctEND IF ‘ ends the conditional statementIF intAnswer <> 52 THEN

PRINT “Wrong ! The correct answer is 52.”END IF ‘ ends the conditional statementEND

Save the program as IfThen.bas.

The above program prompts the user to determine the value of 13 x 4. The value thatthe user enters is stored in the variable intAnswer. It is compared to the value 52 and ifthis is the value entered by the user, the user receives a Correct response, if not, anyother 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 thecondition is true; another action is taken if the condition is false.

Syntax:IF condition THEN

‘Series of statementsELSE

‘Series of statementsEND IF

Page 39: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

39

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 answerPRINT “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.

Page 40: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

40

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.”

ELSEIF intYear < 1969 THEN

PRINT “ Saint Dunstan’s University and Prince of Whales College”PRINT “ were still in operation.”

ELSEPRINT “No. You’re incorrect.”PRINT “Why don’t you ask your teacher?”

END IFEND IFPRINT “Thanks for guessing.”

END

Save the program as Nested.bas.

Page 41: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

41

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

Boolean Operators

OROnly 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 THENPRINT “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”.

Page 42: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

42

ANDBoth 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 intNumberPRINT “Pick a letter: a or b”INPUT strLetter$IF intNumber = 1 AND strLetter$ = “b” THEN

PRINT “You’re lucky!” ELSE

PRINT “Try again”END IFEND

Save the program as And.bas.

NOTIf 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 intAgeIF NOT intAge > 16 THEN

PRINT “You’re a young pup!” ELSE

PRINT “You’re getting old”END IFEND

Page 43: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

43

Save the program as Not.bas.

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

Syntax:Select Case

Case condition‘series of statements

Case condition‘series of statements

...Case Else

‘series of statementsEnd 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 SelectEND

Save the program as Case.bas.

Page 44: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

44

LOOPS

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

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

Syntax: For numeric_variable = start to stop

‘StatementsNext 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 kPRINT “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)

Page 45: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

45

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

Example:For x = 1 to 20

y = x*3If y > 40 then Exit For

Next x

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

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

Syntax:While condition

‘Series of StatementsWend

Example:x = 0 While x < 10

x = x + 1Print x

Wend

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

Do While LoopSyntax:

Do‘Series of statements

Loop While condition

Page 46: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

46

Example:Do

Print xx = x + 1

Loop While x > 10

Example:Do

Print yy = y + 1

Loop While y < 10

Do Until LoopSyntax:

Do‘Series of statements

Loop Until condition

Example:Do

Print xx = x + 1

Loop Until x = 1

Example:Do

Print yy = y + 1

Loop Until y = 10

Page 47: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

47

Structured Programming

The ultimate goal of programming is to write programs that use the least amount ofmemory while accomplishing as much as possible. As programs become larger (andmore complex) organization is the key. Breaking large problems into smaller parts leadsnaturally into using subroutines. 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 subroutineEND SUB

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

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

Global VariablesUsing variables within a subroutine requires that they be declared globally (able to beused anywhere within the program). To declare variables globally, use the Globalstatement.

Syntax:Global variable_name

The variable data type can be commented at the end of the statement.

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

Syntax:CALL Subroutine_name

Page 48: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

48

ExampleCompare 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 variablesGlobal strUserName$ ‘AS StringGlobal strTown$ ‘AS StringGlobal strActor1$ ‘AS StringGlobal strActor2$ ‘AS StringCall GetDataCLSCall DisplayEND‘~~~~~~~~~~~~~~~~~~~~~~~~SUB GetData

REM Get information from userPrint “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 storyPrint “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).”PrintPrint “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.”PrintPrint “And so, “ + strUserName$ + “, this is where the story ends, without spreading”Print “ rumours.”

END SUB

Save the program as Sub.bas.

Page 49: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

49

Graphic User Interfaces (GUI)

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

The NOMAINWIN CommandThe simplest form of the GUI using Liberty Basic can be accomplished using theNOMAINWIN command. In doing this, we eliminate the appearance of the Mainwindow 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 commandThe Notice command will create a Notice dialog box and works the same as the Printcommand.

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

Getting input - Prompt commandThe Prompt command creates a Prompt dialog box, which will include a textbox for theuser to respond in. The Prompt command is followed by a question and a variable.Syntax:

PROMPT “prompting question?”; variable

Example:‘DIM strTeacher$ as StringNOMAINWINPROMPT “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 clickedbefore returning to the code in the Liberty Basic editor.

Page 50: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

50

Creating windows

HandlesAny window that is created in Liberty Basic must be given a nickname or handle. Awindow handle must begin with the pound symbol (#). This identifies the window forLiberty Basic.

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

Open “Title” for window as #handle_name

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

WindowWidth = aWindow Height = b

Both a and b are measured in pixels.

UpperLeftX = xUpperLeftY = y

x represents the number of pixels from the left edge of the screen that the window willopen and y represents the number of pixels from the top of the screen.

Wait CommandThis 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 controlowned by the program. Without having this code, a run-time error will occur.

Page 51: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

51

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 commandThe trapclose command is used to direct program flow when a user uses the X closingbutton or the system close button instead of some other form of exiting a window (like amenu 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 isclosed. Thus, the close event must be trapped. The trapclose command works with allwindow 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 thewindow.

Confirm CommandThe confirm command will automatically display a yes and a no command button in aprompting dialog box.

Syntax:Confirm “message”; string_variable

Page 52: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

52

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 declaredGlobal 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$ENDEnd sub

Save the program as Closing.bas.

Page 53: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

53

Adding controls in a window

Controls like command buttons, checkboxes, radio buttons and textboxes can be addedto a window. For each control that is added, code must be written to tell the programwhat 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 withuser actions made on those controls (clicking, double-clicking, selecting, etc.).

Command ButtonsCommand Buttons can be clicked by the user . When the program is run, and the userclicks on this button, then execution calls the subroutine, passing the handle of thebutton 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 namespecified.

#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 clickedUL - 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.

Page 54: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

54

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

‘**VariablesGlobal 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$ENDEnd sub‘~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Sub OK handle$ Notice “ you clicked the OK button!” Close #handle$End Sub

Save the program as button.bas.

Page 55: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

55

Displaying TextWhen text is used to display information inside a window, it is known as static text. Thistext 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 declaredGlobal strQuit$ ‘Used to store yes or no from the Quit subroutine

‘Do not display main windowNomainwin

‘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"

WaitEND

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

Page 56: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

56

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$ENDEnd sub

Save the program as Text.bas.

Adding TextboxesTextboxes provide a space for a user to type text. They are typically used to collect inputfrom 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 textboxTo insert text into a textbox you need to use the PRINT command and identify thewindow handle, the textbox name and the text you want to insert.

Syntax:Print #handle_name.textbox_name, “message”

Page 57: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

57

Retrieving text from a textbox

To retrieve text from a textbox and assign the text to a string variable, use the Print andthe 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 lineassigns 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

‘**VariablesGlobal 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 windowNomainwin

‘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"

WaitEND

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

Page 58: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

58

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$

ENDEnd sub

Save the program as Textbox.bas.

Creating CheckboxesCheckboxes provide the user several options to choose from and more than one checkbox can be selected at one time. A checkbox displays a box for the user to click and alsoa 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.

Page 59: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

59

Checkbox Commands

Selecting the checkboxThis will make a checkmark appear within a checkbox.

Print #handle_name.CheckBox_name, "set"

Clearing the CheckboxThis will make any checks in the checkbox disappear.

Print #handle_name.CheckBox_name, "reset"

Determining if a checkbox is checkedThis 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

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

‘Do not display main windowNomainwin

‘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"

WaitEND

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

Page 60: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

60

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$

ENDEnd sub

Save the program as Check.bas.

Page 61: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

61

Creating Radio ButtonsRadio buttons allow the user to select only one option at a time, unlike checkboxeswhich allow the user to select several options at the same time. A radio button displays abutton 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 RadioButtonThis will make a dot appear within the radio Button.

Print #handle_name.RadioButton_name, "set"

Clearing the RadioButtonThis will make any dots in the radio button disappear.

Print #handle_name.RadioButton_name, "reset"

Determining if a RadioButton is selectedThis 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 BoxesA 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 whena GUI contains more than one group of check boxes or radio buttons.

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

Page 62: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

62

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 mustbe 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 windowNomainwin

' 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.

Page 63: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

63

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$ ENDEnd sub

Save the program as Radio.bas.

Page 64: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

64

Graphics

Graphics and sound naturally make programs more interesting. Although Liberty Basiccannot display graphics to the extent that the monitors of today are capable of, there arecommands 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, agraphics window is created. The difference between a window and a graphics window isthat the latter will display graphics. It is not advisable to place controls (see GUIsection) 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 backgroundThe 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.

ORPrint #handle_name, “fill red_value green_value blue_value”

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

Example:NomainwinOpen “Nice Background colour” for Graphics as #myDrawingPrint #myDrawing, “fill 214 51 15"wait

Page 65: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

65

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 todeactivate the ability to scroll, the horizscrollbar and vertscrollbar statements must beset 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 StatementThe Flush statement ensures that once grahics are drawn that they “stick”. It may bethe case that code will do nothing unless you make it stick to the window.

Syntax:Print #handle_name, “flush”

Example:

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

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

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

Syntax:Print #handle_name, “down”

Page 66: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

66

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

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

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

Syntax:Print #handle_name, “color predetermined_colour”

ORPrint #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 StatementThe 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.

Page 67: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

67

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

‘** Variables declaredGlobal 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.

Page 68: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

68

The LINE StatementThe 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 theending coordinate of the line.

Example:NomainwinOpen "A Line" for Graphics as #myDrawingPrint #myDrawing, "fill cyan"

Print #myDrawing, "flush"Print #myDrawing, "horizscrollbar off"Print #myDrawing, "vertscrollbar off"

‘ place the pen downPrint #myDrawing, “down”

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

wait

The Place statementThe 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 statementThis 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 changesfor the user.

Syntax:Print #handle_name, “backcolor predetermined_colour”

ORPrint #handle_name, “backcolor red_value green_value blue_value”

Page 69: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

69

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

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

Example:NomainwinOpen "An open rectangle" for Graphics as #myDrawingPrint #myDrawing, "fill 12 22 131"

Print #myDrawing, "flush"Print #myDrawing, "horizscrollbar off"Print #myDrawing, "vertscrollbar off"

‘ place the pen downPrint #myDrawing, “down”

‘ Draw a white rectanglePrint #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 Boxfilledstatement is used. The box will be filled with the colour specified using the Backcolorstatement.

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

Page 70: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

70

Example:NomainwinOpen "A filled rectangle" for Graphics as #myDrawingPrint #myDrawing, "fill 12 22 131"

Print #myDrawing, "flush"Print #myDrawing, "horizscrollbar off"Print #myDrawing, "vertscrollbar off"

‘ place the pen downPrint #myDrawing, “down”

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

wait

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

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

Example:

NomainwinOpen "An open circle" for Graphics as #myCirclePrint #myCircle, "fill brown"

Print #myCircle, "flush"Print #myCircle, "horizscrollbar off"Print #myCircle, "vertscrollbar off"

‘ place the pen downPrint #myCircle, “down”

‘ **continued on next page

Page 71: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

71

Example continued:‘ Draw an orange circlePrint #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, theCirclefilled statement is used. The circlewill be filled with the color specified using theBackcolor statement.

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

Example:

NomainwinOpen "A filled circle" for Graphics as #myCirclePrint #myCircle, "fill cyan"

Print #myCircle, "flush"Print #myCircle, "horizscrollbar off"Print #myCircle, "vertscrollbar off"

‘ place the pen downPrint #myCircle, “down”

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

wait

Page 72: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

72

The Ellipse StatementThis 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 ellipsePrint #handle_name, “ellipsefilled w h”

Example:

NomainwinOpen "Two ellipses" for Graphics as #myEllipsePrint #myEllipse, "fill 127 0 127"

Print #myEllipse, "flush"Print #myEllipse, "horizscrollbar off"Print #myEllipse, "vertscrollbar off"

‘ place the pen downPrint #myEllipse, “down”

‘ Draw an open ellipsePrint #myEllipse, "size 6"

Print #myEllipse, "color pink" Print #myEllipse, "place 40 20" Print #myEllipse, "ellipse 45 20"

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

wait

Page 73: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

73

The Pie StatementThis command will draw a pie slice inside an ellipse of a specified width and height. Thestart and stop angles for the pie must be specified as well. If the second angle ispositive, the pie will sweep clockwise. If the second angle is negative, the pie will sweepcounter-clockwise. Angles are expressed in degrees, and remember there are 360° in acomplete 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 piesPrint #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 windowIn order to display text on a graphics window, the font face and size must first be set.

The Font StatementSyntax:

Print #handle_name, “Font font_face font_size”

font_face is specified by the name of the font. Font names can easily be found inWordPerfect. The entire name of the font must be used, including spaces. If LibertyBasic cannot find the exact font, it will try to match it as close as possible.

font_size represents the size of the font.

Adding TextSyntax:

Print #handle_name, “\text1\text2”Text1 is displayed at the current pen position. The \ causes a carriage return and linefeed and text2 will be displayed under text1. Subsequent lines of text can be added byadding more \.

Page 74: Table of Contents - · PDF filePreface This guide was produced to introduce students to the Liberty Basic programming language. The ... is based on QBasic programming. Liberty Basic

Liberty Basic Beginning Computer Programming

74

Example:

NomainwinOpen "Pies and text example" for Graphics as #myDrawPrint #myDraw, "fill 0 130 0"

Print #myDraw, "flush"Print #myDraw, "horizscrollbar off"Print #myDraw, "vertscrollbar off"

‘ place the pen downPrint #myDraw, “down”

‘ Draw an open piePrint #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 windowTo clear all of the graphics from the window the CLS command can be used. This willremove everything from the window.Syntax:

Print #handle_name, “CLS”