Introduction to Yabasic


About This Guide
Interpreted Program Translation, BASIC, & Yabasic
Getting and Using Yabasic
Statements & Expressions
Data Types & Variables
Operators
Order of Operations (Precedence)
Input and Output
Conditional Control (Selection) Statements
Iteration
Strings
Where to Next?
Example Source Code

About This Guide

This is a brief introduction to the BASIC programming language implemented by the Yabasic interpreter available from http://www.yabasic.de/. The target audience is community college students taking their first- year "computer concepts" classes, most of whom have not taken an operating systems class or formal programming language class. The goal is to provide enough introductory background and information so that Yabasic can be used as a vehicle for demonstrating broad conceptual topics such as computer languages in general; differences between low-level and high-level languages; compilers vs. interpreters; algorithms and basic control structures; and fundamental (flat-file) database concepts.

Computer Concepts classes are about computer concepts in general, not just about programming in particular. This guide is not intended to be a complete BASIC tutorial, nor does it attempt to describe all the features and details of Yabasic. Rather it is intended as a "quick start" and notes to supplement class-room lectures and demonstrations. Only the very essential BASIC statements, functions, and operators will be covered.

[ TOP ]

Interpreted Program Translation, BASIC, & Yabasic

An interpreted computer language is a high-level language that is translated into binary machine code each time it is read from a source file. Disadvantages of interpreted languages frequently mentioned in introductory computer books are mainly that there is a translation time penalty each time the program is run. While true to a degree, several modern interpreted languages, such as Perl, are very highly optimized to be nearly as fast and efficient as a compiled program. Another disadvantage is that the language interpreter (yabasic.exe in this case) must be present on each computer where the program will be used. However, as a development tool, interpreted languages are useful because a program prototype can be written and tested quickly, and since most interpreters step through the program line by line errors are easily localized and identified. Since most assemblers and compilers have a steep learning curve just to master the development environment, interpreters are also ideal as learning tools.

BASIC

BASIC, which is an acronym for Beginner's All-Purpose Symbolic Instruction Code, was developed at Dartmouth College in the 1950's to answer the need for an easy-to-use computer language with a quick response time so that students could see immediate results without waiting for the program to be compiled (which, at that time, could take hours or days!).

The original IBM Personal Computer shipped with a version of BASIC burned into the ROM (Read Only Memory); other vendors included Microsoft GW-Basic as part of the standard operating system files. Beginning with MS-DOS version 5.0 Microsoft included QBasic, the interpreted version of their Quick Basic series of BASIC compilers and Integrated Development Environments that eventually became Visual Basic. QBasic was included on the Windows 95 CD (but not part of the default installation), then dropped on subsequent Windows distributions. It is still available from Microsoft in a file called OLDDOS.EXE (see BASIC Interpreters at http://www.mhuffman.com/resource/index.html#BASIC Note, however, that QBasic does not support Windows long file names, and does not recognize Windows installed printers.

Yabasic

Yabasic (Yet another BASIC) is a relatively recent implementation of a traditional command-line BASIC interpreter. Yabasic continues the tradition of a small, compact, and easy-to-use high-level language interpreter. While Yabasic maintains the main "look and feel" of BASIC, it is not intended to be 100% compatible with other BASIC implementations. In particular, Yabasic includes numerous useful features inherited from various scripting languages and the C programming language. Yabasic is open source, which means, among other things, you can download the source code, modify and redistribute your own version of Yabasic (see the Copyright page at the main Yabasic site).

[ TOP ]

Getting and Using Yabasic

The home page for Yabasic is http://www.yabasic.de/ where you can download a version for Windows or most main Linux distributions. The Windows distribution and installation file is yabasic-X.yyy.bin.exe where X is the major version number (2 as of this writing) and yyy is the minor version number (currently 743). The current Windows binary distribution, yabasic-2.743.bin.exe, is about 260 KB, and requires just under 700 KB of disk space when installed.

Installation

The installation creates a new folder for Yabasic (the default is C:\yabasic\), creates a Start Menu sub-folder for Yabasic, registers the .yab extension, and associates the extension with yabasic.exe in the location where you installed it.

Creating a Yabasic Program

Yabasic source files are ASCII text files and can be written using any text editor. Notepad, available on all Windows systems, will work, but for anything beyond the trivial examples in this guide you will probably want to use a "real" editor that, at the very least, shows you line numbers; allows you to control the width of tab stops and allows you to convert "hard" tab characters (ASCII 09) into equivalent space characters; and will not try to add a .txt extension to all your files. See http://www.mhuffman.com/resource/index.html#EDIT for some freeware and shareware text editors.

It is customary to introduce a language with a trivial program that says "Hello World." Continuing the tradition, here it is in Yabasic:

# hello.yab
# Ubiquitous "Hello World" program in yabasic

Print "Hello, World!"

Execute a Yabasic Program - yab Associated File Type

Save the file as hello.yab. If you installed Yabasic with the installer downloaded from the Yabasic Web site, then all you need to do is double-click on hello.yab. A Windows Console (a.k.a. "Command Prompt", or "DOS" window) should open with the following output:

Hello, World!
---Program done, press RETURN---

Execute a Yabasic Program - Drag & Drop

If you want to execute Yabasic programs on a system were you have not done a complete installation (e.g. on a floppy disk, Zip disk, or flash memory device at school, etc.), the only file you need is yabasic.exe. Copy yabasic.exe to the same folder where your program source file is located, then simply drag the source file on top of yabasic.exe in Windows Explorer.

Execute a Yabasic Program - Command Line

Yabasic is a command-line program. If yabasic.exe is in your PATH, or the same folder as your source file, from the directory where hello.yab is located you can run the program with the following command line:

D:\src_yab>yabasic hello.yab
Hello, World!

D:\src_yab>

Execute a Yabasic Program - Directly from Text Editor

Many text editors include a provision to execute (or compile) source files directly from the editor with a specified program. One good example is metapad from http://liquidninja.com/metapad/download.html. Click on Options>Settings, then enter the full path to your copy of yabasic.exe in the Primary external viewer text box (be sure to include the complete path, including the .exe extension). Then, after saving a Yabasic program in metapad, launch the viewer from the File Menu: File>Launch>Primary Viewer.

[ TOP ]

Statements & Expressions

A Yabasic program is a sequence of statements, which are typically composed of one or more expressions. Fundamental types of statements in most languages, including BASIC and Yabasic, are:

Expressions

An expression is a piece of Yabasic syntax in the form of a calculation that uses operators to combine values and/or variables; and evaluate them to some value. An expression can be used any place where a variable or literal value is used, pretty much like in mathematics.

Statements

A statement is an instruction that Yabasic can execute and tell the computer what to do, not unlike a statement in English: "Turn left on Main Street," "Close the door," etc. The structure of a Yabasic program is line-oriented; statements are terminated at the end of a line when you hit the Enter key and your text editor inserts the Carriage Return/LineFeed pair of characters (ASCII 13, 10) on a Windows system. Multiple statements in one physical line are permitted; they must be separated by a colon. Unfortunately, there is no provision to split long statements over more than one physical line.

Comments

Comments are text in a Yabasic program that are meant for people to read for additional information, but are not seen or evaluated by the Yabasic interpreter. Comments can be entered (delimited) in 3 ways:

# "hash" / "pound" / "sharp" character must be 1st character on line
# (no leading white space!)
    Rem this is a "remark" statement, leading white space OK

price = 12.50           // assignment statement
tax = price * 0.04      // result of expression assigned to variable

// multiple statements on one line separated by a colon
r = 3 : area = 3.14159 * r * r      : Rem calculate area

It seems to be common to write "block level comments" (comments that describe a major section of a program) using the # comment delimiter, and "in- line comments" using //. If you prefer you can use // for all comments to avoid confusion.

[ TOP ]

Data Types & Variables

Yabasic has 4 main data types:

All Yabasic numbers are represented internally as double precision floating point numbers; and strings are a primitive type. there is no integer type or character type in Yabasic.

Numbers and strings can be referenced by their literal representation, as in the examples above, or assigned to variables. Variables are named locations in memory where the actual data value is stored. Variable names may begin with either an alphabetic character (A-Z, a-z) or the under-score character (_) and may contain the digits 0-9 (note that variable names cannot begin with a digit). If the data type is a string, or an array of strings, the variable name must end with a dollar sign ($).

Variable names that will be used to store arrays must be declared before they are used for the first time with the Dim keyword. The declaration must also include the size of the array. (Technically, the declaration specifies an integer that is the index of the last array element, it is actually 1 less than the array size.)

Notes:

Examples:
# "primitive" data types assigned to variables
count = 10                  // a real number, used as an integer
balance = 1135.49           // a real number, used as a float
lastName$ = "Flintstone"    // a character string
ch$ = "Q"                   // single characters are just 1-character strings

# "aggregate" data types assigned to variables
Dim num_array(3)            // array of 4 numbers: (indices 0, 1, 2, 3)
num_array(0) = 14           // first element in num_array
num_array(2) = -100         // third element in num_array

Dim str_array$(9)           // array of 10 strings: (indices 0, 1, ..., 9)
str_array$(0) = "foo"       // first element in str_array

# Be careful with spelling and case sensitivity!
price = 12.50
tax = price * 0.04
Total = Price + tax         // oops! 'Price' is a new variable, given value of 0!

Note that array indices in BASIC (including Yabasic) are enclosed in parentheses ("round brackets") following the variable name. Most other languages use square brackets; just one of several differences to keep in mind if you move between languages.

[ TOP ]

Operators

The assignment operator in Yabasic is = as shown in the variable assignment examples above. Assignment statements must begin with a variable name (you cannot make an assignment as part of an expression).

Yabasic uses mostly familiar and intuitive operators for arithmetic:

Arithmetic Operators

Operator Function Example
+ Addition 2 + 4.5, price + tax
- Subtraction 10 - 2.75, price - credit
* Multiplication 65 * 0.15, total * discount
/ Division 76 / 85, score / total
**, ^ Exponentiation 2**8, num ^ power

Most BASIC's have a MOD operator for modulus (remainder) division; Yabasic implements modulus with the mod() function.

Boolean conditions (named after George Boole), or comparisons between values, are made with the relational operators.

Relational Operators

Operator Function Example
= Equal to i = 10, count = max_count
<> Not equal i <> max_count
< Less than i < 10, num_files < max_files
<= Less than or equal i <= 10, num_files <= max_files
> Greater than total > 100, num_errors > max_errors
>= Greater than or equal total >= 100, num_errors >= max_errors

Note that many high-level languages derived from or inspired by the C programming language use == for equality and != for inequality. Also note that in BASIC (including Yabasic) the = operator serves two functions: equality in comparison expressions, and the assignment operator; the BASIC interpreter can distinguish the difference from the context of the expression.

Logical conditions can be combined to form more complex expressions using the and, or, and not operators.

Logical Operators

Operator Function Example
and Logical and i > 10 and i < 20
or Logical or ch$ = "q" or ch$ = "Q"
not
!
Logical not not(col_num > 80 and line_num > 25)
[ TOP ]

Order of Operations (Precedence)

Operators in BASIC, like in mathematics, have an order of evaluation, or precedence. Generally they obey the same rules: exponentiation happens before multiplication and division, which happens before addition and subtraction. Also like in math, you can override the normal order with the use of parentheses, which have the highest precedence. In fact, there is no harm using parentheses even if not strictly needed; frequently they make a compound expression easier to understand.

If an expression contains more than one operator with the same precedence then the operators are evaluated from left to right (technically called associativity).

Operator Precedence

Order Operator
1 Parentheses ()
2 Negation unary -
3 Exponentiation **, ^
4 Multiplication, division *, /
5 Addition, subtraction +, -
6 Comparison =, <, >, <=, >=, <>
7 Logical NOT Not
8 Logical AND And
9 Logical OR Or

Note one slight difference between Yabasic and MS QBasic: unary minus has higher precedence in Yabasic than exponentiation. (In fact, this differs from other high-level languages as well, notably Perl and Python, so it might not be intentional.)

Print -2 ^ 4    : REM Yabasic =  16
                  REM QBasic  = -16

Print (-2) ^ 4  : REM Yabasic =  16
                  REM QBasic  =  16
[ TOP ]

Input and Output

Use the Input statement to get information into the program from the keyboard (technically called standard input, or STDIN; use the Print statement to get information out of the program and onto the console (technically called standard output, or STDOUT. The following Yabasic statements will prompt the user for a name and then issue a greeting:

# input.yab
# yabasic input/output example

input "Enter your name: "  name$                    // get user name
print "Hello ", name$, ", welcome to CIS 120!"      // say hello
Output:
Enter your name: Fred
Hello Fred, welcome to CIS 120!

The Input statement takes an optional prompt string in quotation marks followed by a comma separated variable list (but no comma between Input and the prompt string). It is generally best to only fill one input variable for each Input statement. Notice how any extra spaces must be included inside the quoted strings in the Print statement; the commas separating the Print arguments cause the arguments to run together. Most other BASICs use a semi-colon for the same effect.

While variable names are case sensitive in Yabasic, keywords like Input and Print are not case sensitive. The example above could have used INPUT and PRINT, or even input and print.

[ TOP ]

Conditional Control (Selection) Statements

The Yabasic control statement that allows a program to branch to different areas based on some condition is If...Then...Else.

# if.yab
# yabasic conditional example 1 (if)

Input "What is your total order? " order    // what did customer spend?

If ( order < 100 ) Then                     // test first condition
    discount = order * .1
Endif

If ( order >= 100 ) Then                    // test second condition
    discount = order * .15
Endif

Print "Your discount is $", discount        // display results
Output:
What is your total order? 60
Your discount is $6

What is your total order? 120
Your discount is $ 18

Another way to write the test condition and achieve the same results uses the Elseif keyword. Elseif makes the original statement a bit more compact, and also makes it easy to add additional conditions.

# elseif.yab
# yabasic conditional example 2 (elseif)

Input "What is your total order? " order    // what did customer spend?

If ( order < 100 ) Then
    discount = order * .1

Elseif ( order < 500 ) Then             // better, clearer that we are
    discount = order * .15              // doing an "either - or" test

Else                                    // easy to add 3rd test
    discount = order * .2               // big spender gets big discount

Endif

Print "Your discount is $", discount    // display results
Output:
What is your total order? 80
Your discount is $ 8

What is your total order? 200
Your discount is $ 30

What is your total order? 600
Your discount is $ 120
[ TOP ]

Iteration (Loops)

The Yabasic control structures that allow a program to repeat a section of code more than once based on the value of a condition are While...Wend and For...Next. Yabasic also supports a Repeat...Until loop construct, which tests the condition at the end of the loop, and a Do...Loop which is a "condition less", or infinite loop.

All loops can be written with one basic form, such as While...Wend, although the additional forms permit more expressive ways to implement different types of logic. When the number of repetitions is known in advance, the For...Next loop is generally preferred.

Here is a simple loop:

# loop1.yab
# yabasic loop example 1 (While...Wend and For...Next)

Print "A simple loop using While...Wend"
i = 0                       // loop index counter
max_num   = 10              // biggest number to print

While (i <= max_num)
    Print i;                // display value of loop index
    i = i + 1               // IMPORTANT! increment the index so
Wend                        //   we don't have an infinite loop
Print                       // new line
Print                       // blank line for visual spacing

Print "A simple loop using For...Next"
For i = 0 TO 10             // when the number or iterations are
    Print i;                //  known in advance this form is
Next i                      //  "self-documenting
Print                       // new line
Print                       // blank line for visual spacing
Output:
A simple loop using While...Wend
0 1 2 3 4 5 6 7 8 9 10

A simple loop using For...Next
0 1 2 3 4 5 6 7 8 9 10

The While...Wend loop tests whether the condition is TRUE or FALSE at the beginning of the loop. If, going into the loop, the condition is FALSE the program code in the body of the loop will never execute. See the next example where we "pre-load" the condition variable with a value guaranteed to test TRUE so that we ensure the code in the loop body executes at least one time.

Note in the While...Wend loop the importance of doing something that will eventually result in the condition returning FALSE. If the condition variable never changes, the loop will execute forever (assuming the initial condition value was TRUE) resulting in an infinite loop.

Also note that in the For...Next the upper limit (10 in the example) is inclusive; to achieve the same logic with While...Wend we used the <=operator.

This next loop is a bit more involved; it prompts the user for a number and saves it in a variable called sum, then enters a loop where it prompts for another number to add to sum. Note how, before entering the loop, the answer variable is pre- loaded to force at least one pass through the loop. At the end of each loop the user is asked if she wants to continue. Note also how the response is converted to upper case to simplify the test for a "no" answer.

# loop2.yab
# yabasic loop example 2 (While...Wend with pre-loaded condition)

# add numbers until user says no
Input "Enter first number: " sum    // get first number to get started

answer$ = "Y"                       // assume user wants to continue
While (answer$ <> "N")              // loop until user answers no
    Input "Enter next number: " n   // get next number

    sum = sum + n                   // add next number to sum
    Print "Sum = ", sum             // display the sum
    Input "Continue? " answer$      // add another number?
    answer$ = Upper$(answer$)       // convert to upper case so only
Wend                                //   one char is tested
                                    // NOTE: some BASICS use Ucase$()
Output:
Enter first number: 4
Enter next number: 5.6
Sum = 9.6
Continue? y
Enter next number: 3.1
Sum = 12.7
Continue? n

Most high-level languages support more than one looping construct so that you can write code that better expresses your logic. Yabasic has a Repeat...Until loop that guarantees the loop will execute at least once. This is exactly what we want to do, and it does not require us to "pre-load" the test condition variable like in the example above.

# loop3.yab
# yabasic loop example 3 (Repeat...Until tests condition at end of loop)

# add numbers using a "post condition" loop
Input "Enter first number: " sum            // get first number
Repeat
    Input "Enter next number: " n           // get next number
    sum = sum + n                           // add next number to sum
    Print "Sum = ", sum                     // display the sum
    Input "Continue? " answer$              // add another number?
Until (answer$ = "n" Or answer$ = "N")      // test upper and lower case
[ TOP ]

Strings

BASIC has several useful functions to manipulate and work with text (the string data type). mid$(), left$(), and right$() extract sub strings from larger strings based on a numerical index. Use instr() to search a string for a sub string (which can be a single character) to get the index (rinstr() does a "reverse" search, starting from the end of the string). Yabasic adds an extremely handy function called token() that splits a string into an array of smaller strings based on a separator string. The Yabasic documentation describes all the supported functions and provides good examples for most of them.

Here is an example of how you might extract various pieces of a data record to build a string for a report:

# string1.yab
# yabasic text manipulation example 1 (mid$())


      //          1         2
      // 12345678901234567890
name$ = "John Paul Jones"

Print "Name (First, Middle, Last): ", name$

first$ = mid$(name$, 1, 4)              // start at pos 1, get 4 characters
middle$ = mid$(name$, 6, 4)             // start at pos 6, get 4 characters
last$ = mid$(name$, 11, 5)              // start at pos 11, get 5 characters

Print "Name (Last, First, Middle): ";
Print last$, ", ", first$, " ", middle$     // print last name first
Output:
Name (First, Middle, Last): John Paul Jones
Name (Last, First, Middle): Jones, John Paul

Note that while array offsets start at 0, the string functions in BASIC (and Yabasic) start counting string indices at 1. This inconsistency is an annoyance, but sometimes backward compatibility is a powerful force...

Here is a way to handle extracting pieces of a string when you don't know where or how long the individual pieces are. Note how the string length function len() is used as a loop upper bound control; then mid$() extracts one character at a time, checking for a blank space. Each character is then concatenated (look it up in a dictionary!) to a new string.

# string2.yab
# yabasic text manipulation example 2

name$ = "John Paul Jones"

i = 1
While (i < len(name$))
    ch$ = mid$(name$, i, 1)     // get character at index i
                                // look for first space
    If (ch$ = " ") Break        //  (1-line form of If)

    first$ = first$ + ch$       // build first name from characters
    i = i + 1                   // increment loop counter
Wend

Print first$                    // display the first name

Note the special "one-line If" statement does not use the Then keyword. Also note use of the Break key word to break out of the While loop when the space character is found.

BASIC makes it easy to get ASCII character codes from string characters and convert them to hexadecimal. Application of some other concepts in this discussion (input/output, loops) could turn the following example into a useful utility...

# asc_code.yab
# yabasic text manipulation example 3 ASCII code and hex conversion

ch$ = "A"                           // assign "A" to 1-character string

code = ASC(ch$)                     // get ASCII character code of ch$
                                    // display ASCII code in decimal and hex

Print "ASCII ", ch$, " = ", code, " Decimal"
Print "ASCII ", ch$, " = ", hex$( code ), " Hexadecimal"
Output:
ASCII A = 65 Decimal
ASCII A = 41 Hexadecimal
[ TOP ]

Where to Next?

Yabasic has much more capability than this brief discussion covers; indeed the intent is a "quick start" guide for non-programmers in a computer concepts class. The Yabasic documentation (yabasic.htm in the Yabasic distribution) has good descriptions of all the functions and keywords as well as many examples of usage. Run the examples on this page in Yabasic then experiment by making small, incremental modifications to see what happens. You can download the source files from the link below, or you can copy the code from the examples into a text editor and save them as Yabasic source files. The usual extension for BASIC source files is .bas, however I have followed the format used by the author of Yabasic and used the .yab extension.

The best way to learn a language, like learning to play a musical instrument, is to jump in and practice. Look at some examples in the Help topics for various keywords and try to put a few together to do something useful. However, unlike learning a new musical instrument, at least you won't annoy the neighbors or make the dog howl...

[ TOP ]

Example Source Code

The following archive contains the example Yabasic programs with a file name as indicated in the comment header for each program example above.
src_yab.zip:   http://www.mhuffman.com/notes/language/src_yab/src_yab.zip

[ TOP ]

Copyright Notice

Introduction to Yabasic Copyright © 2004 Michael B. Huffman

The author gives general permission to copy and distribute this document in any medium provided that all copies contain an acknowledgement of authorship and the URL of the original document:  http://www.mhuffman.com/notes/language/yab_intro.html

Mike Huffman:  mike@mhuffman.com

[ TOP ]
Revised: 12 APR 2004 21:59