QBASIC

Introduction

    This tutorial is laid out in what I believe to be a good order for learning QBasic. I have been frustrated often because the QBasic help menu has not explained things to me well enough. If you have seen the QBasic help menus you'll know that they use very formal language. This tutorial was written more casually, so you should be able to catch on fairly quickly. I hope that this document helps you get what you want out of QBasic.

Command: PRINT

    PRINT can be used in many ways. If you were to use PRINT without any parameters, it would simply cause the cursor to move down one row and return to the left side of the screen (also known as a carriage return). This does us not much good, but now you know. To print the word QBASIC on the screen, you would need PRINT "QBASIC" in your program- pretty easy. You may also print numbers on the screen in two different ways. One is PRINT "2000". The other way is PRINT 2000. The first way is printing 2000 as text, while the second is printing it as a number. Printing numbers in this way is not very practical, but it is more often used for displaying the values that variables have been assigned. Later on in the section about variables, I will show you how to use a variable in the PRINT command.

   PRINT "This is how to use the PRINT command"

   PRINT

   PRINT "It's amazing!"

   PRINT 2000

   PRINT "The number is: "; 2000



Output:

   This is how to use the PRINT command



   It's amazing!

   2000

   The number is: 2000

Command: CLS

    Once we have a bunch of words on the screen, they can get rather annoying. Well, what do you know! There is something you can do about it. CLS is probably the simplest command in QBasic. There is one way to use the CLS command; type it in. When QBasic executes this command, the screen is cleared and the cursor returns to the top left corner of the screen.

   PRINT "This line of text is going to be erased"

   CLS

   PRINT "Only these words are on the screen"



Output:(At top left corner of screen)

   Only these words are on the screen

Command: BEEP

    Of course, there is much more to programming than text. The BEEP command when in a program makes the speaker make a tone for about a half a second. This is a very old command, but it works for teaching. You will learn how to produce different frequencies and lengths of sound later.

   CLS

   PRINT "The speaker is going to beep!"

   BEEP

   PRINT "Cool!"

Output:

   The speaker is going to beep!

     (speaker emits tone)

   Cool!

Tool: REM

    Before we get any further, it would be a good idea to know how to explain your programs within the source code without affecting the program. You can do this using the REM (remark) command. To make a remark in your program type REM followed by any text that you want. REM causes QBasic to ignore everything on the line that is to the right of it. Take a look at the example.

   REM This program demonstrates the REM command

   PRINT "The REM command won't work if inside quotes"

   REM Here is another remark line

   REM You can have many remarks in a program



Output:

   The REM command won't work if inside quotes

Command: END

    In the case that you want to stop the running of your program even though there are more lines of commands (this is applicable mainly in debugging), the END command is what you need. END will trick QBasic into thinking that there are no more lines to run and it will return you to the editor. You may not use this command for some time, but it is just something to know.

   REM The END command will stop the program"

   PRINT "First line of text"

   PRINT "Second line of text"

   END

   PRINT "Third line of text

   PRINT "The third and fourth lines won't be displayed"

   REM Oh well!



Output:

   First line of text

   Second line of text

Command: GOTO

    Now we get into the more complex part of QBasic. The GOTO command will make QBasic run lines of commands in different order than what they are written. At the moment, there is not much use for this, but later you will see that it is very important. The GOTO command requires that you have a destination for it. You have to tell it where you want the program execution to go. This is called a line number. In earlier versions of Basic, every line in the program was required to have a line number. This is not so any more. In QBasic, the line number (or label) can be either a number, a word, of a combination of the two as long as you only have that combination as a label once in the program.

   PRINT "Line of text #1"

   GOTO 10

   PRINT "This line gets skipped"

   10:

   PRINT "Line of text #2"

   PRINT

   GOTO abcd

   PRINT "QBasic will not execute this line either"

   abcd:

   PRINT "Line of text #3"

 

Output:

   Line of text #1

   Line of text #2



   Line of text #3

    As you can see, each label must be followed by a : in order for it to work. Also, the labels "10" and "abcd" only appeared as labels once in the program. This does not mean that you may only have one GOTO 10 command in the program; you can have as many as you need. This will be demonstrated later.

Concept: Variables

    Before learning any more commands, you now must learn about variables. A variable in it's simplest form is a letter or word that represents a number that it has been assigned. Examples of QBasic numerical variables are: x, y, num, hjk1, d45. (A variable may contain numbers as long as it starts with a letter.) QBasic variables are NOT case sensitive. For example: x = X and hjk1 = hJK1. Once a variable has been assigned a number, it will be the equivalent to that number.

   REM Syntax for assigning variables

   x = 25

   q = 4

   op1 = 17



    (There is no output for this program)

    Once these lines have been executed, the variable x, y, and op1 will be numerically equivalent to 25, 4, 17 respectively. But I can't do anything with them yet. Well, Remember before when I talked about using variables in the print command? This is where they fit in. In the example x and q are assigned values using the = sign and then using PRINT the values are displayed onto the screen.

   CLS

   x = 25

   q = 4

   PRINT x

   PRINT q



Output:

   25

   4

Command: IF. . .THEN. . .ELSE

    The "IF...THEN...ELSE" command bring variety into a program. It is the main controller of program line execution (the way the program runs). When an IF...THEN statement is executed, QBasic evaluates the criteria for decision and directs the program flow accordingly. Look at this example line of code:

   IF A = 1 THEN GOTO 100

    The criteria for this IF...THEN statement to send the program flow to line 100 is for the variable `A' to hold a value of 1. If, in this case, the value of `A' does not equal 1, the program would continue execution onto the following line of the program. Now we add the ELSE part of the command:

   IF B = 1 THEN GOTO 100 ELSE GOTO 200

    The ELSE part of this command is optional. The reason for it is to allow for the criteria of the IF...THEN statement not to be met. In the above example, let us say that B = 3. Since B does not equal 1, the command after THEN (GOTO 100) is not executed but rather the one after ELSE (GOTO 200). The completely literal description for this IF...THEN statement is: If the value of `B' is 1, continue running the program at line 100, but if NOT, continue to line 200 instead. You must realize that the GOTO command is not the only one that can be used in this statement. Any other command can be executed via IF...THEN statements such as CLS, BEEP, PRINT, etc. Here are a few of the formats of different kinds of variables in IF...THEN statments:

   IF A = 1 THEN... If `A' equals 1

   IF A > 1 THEN... is greater than 1

   IF A <= 1 THEN... is less than or equal to 1

   IF A <> 1 THEN... does not equal one

    Some examples of using the IF...THEN command for something other than GOTO:

   IF A = 1 THEN PRINT "Well what do you know? A = 1"

   IF A = 2 THEN BEEP

   IF A = 3 THEN N = 15

    If you want, you could copy the above three examples and put them into a program. When QBasic gets to those lines, they evaluate the value of `A' and choose what commands to execute. If `A' is 1 it prints a message, if 2 it beeps, if 3 it sets that value of `N' to 15. This may sound complex at first, but once you learn it, the concept is really quite simple.

Command: FOR. . .NEXT

    One of the most time saving commands (both programming time and processing time) is the FOR...NEXT command. A single FOR...NEXT loop involves only one variable, but that one variable has very valuable characteristics. The syntax for the command is:

   FOR variable = beginning_number TO end_number

   .

   .

   .

   NEXT variable

    For example:

   FOR T = 1 to 5

   PRINT T

   NEXT T



Output:

   1

   2

   3

   4

   5

    The variable `T' was put into a loop, increasing by 1 for each time the cycle was run. Any commands inside the FOR...NEXT loop that depend on the variable `T' are affected. In the above example, as you can see, when the PRINT command displayed the value of `T' it had incremented by one for each time around the loop. One of the valuable aspects of FOR...NEXT is in animation. That is way more advanced, but just as an example, the FOR...NEXT loop makes it easy to "drag" a picture across the screen with a simple loop that changes its coordinates. Sound tricky? Sorry if it confuses you. Never mind then.

    If you are the type that always wants to know more, here is something for you. To get a variable to count downward, do this:

   FOR T = 10 to 1 STEP -1

   .

   .

   NEXT T

    Or you could get it to count up (or down using a `-' sign) by a specific increment like this:

   FOR T = 1 to 100 STEP 10

   .

   .

   NEXT T

Conclusion

    This tutorial can merely instruct you on the basics of QBasic. There are hundreds of commands/functions used in QBasic. Refer to the Advanced Tutorial for learning specifics on individual QBasic commands. The Advanced Tutorial is index-based to make the locating of specific information easier.

END

Description:
This statement is used to immediately terminate execution of a program.
 If any files or devices are still open (see CLOSE) when execution is terminated, then Just BASIC will close them and present a dialog expressing this fact. 
It is good programming practice to close files and devices before terminating execution.

Note:  The STOP statement is functionally identical to END and is interchangable. 
Also, make sure that when a program is finished running that it terminates properly with an END statement. 
Otherwise the program's windows may all be closed, giving the illusion that it has stopped running, but it will still be resident in memory and may still consume processor resources.

Usage:

  print "Preliminary Tests Complete."

[askAgain]

  input "Would you like to continue (Y/N) ?"; yesOrNo$

  yesOrNo$ = left$(yesOrNo$, 1)

  if yesOrNo$ = "y" or yesOrNo$ = "Y" then [continueA]

  ifYesOrNo$ = 'n" or yesOrNo$ = "N" then end

  print "Please answer Y or N."

  goto [askAgain]

[continueA]

...some more code here...

end  'more than one end statement is allowed

 

 

 

 

IF test expression THEN expression(s)

IF test expression THEN expression(s)1 ELSE expression(s)2

IF test expression THEN

    expression(s)1

END IF

 

IF test expression THEN

    expression(s)1

ELSE

    expression(s)2

END IF

 

Description:

The IF...THEN statement provides a way to change program flow based on a test expression.
 For example, the following line directs program execution to branch label [soundAlarm] if fuel runs low.

if fuel < 5 then [soundAlarm]

Another way to control program flow is to use the IF...THEN...ELSE statement.  This extended form of IF...THEN adds expressiveness and simplifies coding of some logical decision-making software.  Here is an example of its usefulness.

Consider:

[retry]

  input "Please choose mode, (N)ovice or e(X)pert?"; mode$

  if len(mode$) = 0 then print "Invalid entry! Retry" : goto [retry]

  mode$ = left$(mode$, 1)

  if instr("NnXx", mode$) = 0 then print "Invalid entry! Retry" : goto [retry]

  if instr("Nn", mode$) > 0 then print "Novice mode" : goto [main]

  print "eXpert mode"

[main]

  print "Main Selection Menu"

The conditional lines can be shortened to one line as follows:

if instr("Nn",mode$)> 0 then print "Novice mode" else print "eXpert mode"

Some permitted forms are as follows:

  if a < b then statement else statement

  if a < b then [label] else statement

  if a < b then statement else [label]

  if a < b then statement : statement else statement

  if a < b then statement else statement : statement

  if a < b then statement : goto [label] else statement

  if a < b then gosub [label1] else gosub [label2]

Any number of variations on these formats are permissible.  The (a < b) BOOLEAN expression is of course only a simple example chosen for convenience.  It must be replaced with the correct expression to suit the problem.

IF...THEN...END IF is another form using what are called conditional blocks.  This allows great control over the flow of program decision making.  Here is an example of code using blocks.

    if qtySubdirs = 0 then

        print "None."

        goto [noSubs]

    end if

 

A block is merely one or more lines of code that are executed as a result of a conditional test.  There is one block in the example above, and it is executed  if qtySubdirs = 0.

It is also possible to use the ELSE keyword as well with blocks:

    if qtySubdirs = 0 then

        print "None."

      else

        print "Count of subdirectories: "; qtySubdirs

    end if

 

This type of coding is easy to read and understand.  There are two blocks in this example.  One is executed  if qtySubdirs = 0, and one is executed if qtySubdirs is not equal to 0.  Only one of the two blocks will be executed (never both as a result of the same test).

 

These conditional blocks can be nested inside each other:

    if verbose = 1 then

        if qtySubdirs = 0 then

            print "None."

          else

            print "Count of subdirectories: "; qtySubdirs

        end if

    end if

 

In the example above, if the verbose flag is set to 1 (true), then display something, or else skip the display code entirely.

See also:  Select Case, Conditional Statements, Boolean Evaluations

SELECT CASE is a construction for evaluating and acting on sets of conditions.  The syntax for Select Case is:

SELECT CASE var

    CASE x

        'basic code

        'goes here

    CASE y

        'basic code

        'goes here

    CASE z

        'basic code

        'goes here

    CASE else

        'basic code

        'goes here

    END SELECT

 

SELECT CASE var  - defines the beginning of the construct.  It is followed by the name variable that will be evaluated. 
The variable can be a     numeric variable or a string variable, or an expression such as "a+b".

CASE value - following the SELECT CASE statement, are individual CASE statements, specifying the conditions to evaluate for the selected variable. Code after the "case" statement is executed if that particular case evaluates to TRUE.  There is no limit to the number of conditions that can be used for evaluation.

CASE ELSE - defines a block of code to be executed if the selected value does not fulfil any other CASE statements.

END SELECT - signals the end of the SELECT CASE construct.

 

Example usage:

num = 3

select case num

    case 1

        print "one"

    case 2

        print "two"

    case 3

        print "three"

    case else

        print "other number"

    end select

 

The example above results in output in the mainwin of:

 

Strings

SELECT CASE can also evaluate string expressions in a similar way to numeric expressions.

 

String example:

 

var$="blue"

 

select case var$

    case "red"

        print "red"

    case "green","yellow"

        print "green or yellow"

    case else

         print "color unknown"

end select

 

MULTIPLE CASES - may be evaluated when separated by a comma.

For example:

  select case a+b

    case 4,5

      do stuff

    case 6,7

      do other stuff

  end select

 

Evaluating multiple conditions in the CASE statement

Omitting the expression (or variable) in the SELECT CASE statement causes the conditions in the CASE statements to be evaluated in their entirety.  To omit the expression, simply type "select case" with no variable or expression after it.  In the following example, since "value" evaluates to the first CASE statement, the printout says "First case"

 

'correct:

value = 58

select case

    case (value < 10) or (value > 50 and value < 60)

        print "First case"

    case (value > 100) and (value < 200)

        print "Second case"

    case (value = 300) or (value = 400)

        print "Third case"

    case else

        print "Not evaluated"

end select

 

Nested statements

Nested select case statements may be used.  Example:

  select case a+b

    case 4,5

      select case c*d

        case 100

          do stuff

      end select

      do stuff

    case 6,7

      do other stuff

  end select

DO and LOOP cause code to be executed while a certain condition evaluates to true, or until a certain condition evaluates to true. The "while" and "until" parts of this expression can be located either in the "DO" statement or the "LOOP" statement. The following form is good for cases when you want a loop that always executes once and then only loops back as long as a condition is met. It will continue looping back and executing the code as long as the booleanExpr evaluates to true.

    'execute the code inside this loop at least once

    do

        'code in here

    loop while booleanExpr

 

You can also use the UNTIL keyword to reverse the logic of the expression:

 

    'execute the code inside this loop at least once

    do

        'code in here

    loop until booleanExpr

 

Usage:

 'examples using "loop while" and "loop until"

    print "print a zero"

    do

        print a

        a = a + 1

    loop while a > 10

    print

 

    print "print 1 to 9"

    do

        print a

        a = a + 1

    loop while a < 10

    print

 

    'examples using loop until

    print "print a zero"

    do

        print b

        b = b + 1

    loop until b = 1

    print

 

    print "print 1 to 9"

    do

        print b

        b = b + 1

    loop until b = 10

 

examples using loop while

    print "print 1 to 3"

    a = 1

    do while a <= 3

        print a

        a = a + 1

    loop

 

    print

 

    print "print 9 to 7"

    b = 9

    do until b = 6

        print b

        b = b - 1

    loop

    print

 

    print "don't print anything"

    do while c = 10

        print c

        c = c + 1

    loop

    end

 

FOR

Description:

The FOR . . . NEXT looping construct provides a way to execute code a specific amount of times. See the section below on the proper way to exit a loop before the counter variable reaches the limit.  A starting and ending value are specified:

    for var = 1 to 10

      {BASIC code}

    next var

In this case, the {BASIC code} is executed 10 times, with var being 1 the first time, 2 the second, and on through 10 the tenth time. 
Optionally (and usually) var is used in some calculation(s) in the {BASIC code}. For example if the {BASIC code} is  print var ^ 2, then a list of squares for var will be displayed upon execution.

 

The specified range could just as easily be 2 TO 20, instead of 1 TO 10, but since the loop always counts +1 at a time, the first number must be less than the second.  The way around this limitation is to place STEP n at the end of for FOR statement:

    for index = 20 to 2 step -1

      {BASIC code}

    next index

This loops 19 times returning values for index that start with 20 and end with 2.  STEP can be used with both positive and and negative numbers and it is not limited to integer values.  For example:

    for x = 0 to 1 step .01

      print "The sine of "; x; " is "; sin(x)

    next x

 

 

INPUT

INPUT  #handle  "string expression";  variableName

Description: This command has several possible forms:

    input var

This form causes a program to stop and wait for user to enter data in the program's mainwin and press the 'Return' key.  It will then assign the data entered to var.

    input "enter data"; var 

This form will display the string "enter data" and then stop and wait for user to enter data in the program's mainwin and press 'Return'.  It will then assign the data entered to var.

    input #name, var

This form will get the next data item from the open file or device using handle named #handle and assign the data to var.  If no device or file exists that uses the handle named #handle, then INPUT returns an error.

input #name, var1, var2

This form causes the next two data items to be fetched and assigned to var1 and var2.

    line input #name, var$

The LINE INPUT statement will read from the file, ignoring commas in the input stream and completing the data item only at the next carriage return or at the end of file.  This is useful for reading text with embedded commas

Usage:

  'Display a text file

  filedialog "Open..." , "*.txt", filename$

  open filename$ for input as #text

[loop]

  if eof(#text) <> 0 then [quit]

  input #text, item$

  print item$

  goto [loop]

[quit]

  close #text

  print "Done."

  end

 

Arrays

t is possible to use Input and Line Input to fill arrays directly.  To input directly to an array:

    input array$(x)

It is also possible to use this method:

    input array$(x), string$, stuff(i)

Question Mark

Most versions of Microsoft BASIC implement INPUT to automatically place a question mark on the display in front of the cursor when the user is prompted or information:

  input "Please enter the upper limit"; limit

  produces:

    Please enter the upper limit ? |

Just BASIC makes the appearance of a question mark optional.

  input "Please enter the upper limit :"; limit

  produces:

    Please enter the upper limit: |

  and:  

 input limit  

 produces simply:

    ? |

In the simple form input limit, the question mark is inserted automatically, but if a prompt is specified, as in the above example, only the contents of the prompt are displayed, and nothing more.  If it is necessary to obtain input without a prompt and without a question mark, then the following will achieve the desired effect:

  input ""; limit

Additionally, in most Microsoft BASICs, if INPUT expects a numeric value and a non numeric or string value is entered, the user will be faced with a comment something like 'Redo From Start', and be expected to reenter.  Just BASIC does not automatically do this, but converts the entry to a zero value and sets the variable accordingly. 

The prompt may be expressed as a string variable, as well as a literal string:

  prompt$ = "Please enter the upper limit:"

  input prompt$; limit

See also: INPUT$(#h, n),Line Input

 

PRINT

PRINT #handle, expression ; expression(s) ;

Description:

This statement is used to send data to the mainwin, to a disk file, or to other windows.  A series of expressions can follow PRINT, each separated by a semicolon.  Each expression is displayed in sequence.  If the data is being sent to a disk file, or to a window, then #handle must be present.

PRINTing to the mainwin:

After the expressions are displayed, the cursor (that blinking vertical bar | ) will move down to the next line, and the next time information is sent to the window, it will be placed on the next line down.  To prevent the cursor from moving immediately to the next line, add an additional semicolon to the end of the list of expressions.  This prevents the cursor from being moved down a line when the expressions are displayed.  The next time data is displayed, it will be added onto the end of the line of data displayed previously.

Usage:                  Produces:

  print "hello world"           hello world

  print "hello ";               hello world

  print "world"

  age = 23

  print "Ed is "; age; " years old"     Ed is 23 years old

When sending data to a disk file and in regard to the use of the semicolon at the end of the expression list, the rules are similar, although the result is not displayed on the screen.  Use of a semicolon at the end of a line suppresses the carriage return/line feed that causes text to be printed on the next line.  When printing to a window, the expressions sent are usually commands to the window (or requests for information from the window).  For more information, see GUI Programming.

 

Just BASIC supports user defined functions and subroutines.  They look similar to their QBASIC equivalents:

  'define a function for returning a square root

  function squareRoot(value)

    squareRoot = value ^ 0.5

  end function

and...

 

  'create a subroutine for logging to an event log

  sub logToFile logString$

    open "c:\logdir\event.log" for append as #event

    print #event, time$()

    print #event, logString$

    close #event

  end sub

 

A user-defined function such as the one above can be treated like any built-in function:

  print "The square root of 5 is "; squareRoot(5)

Subroutines in Just BASIC are accessed using the CALL statement.  For example:

  'Now log some info to disk

  call logToFile "The square root of 5 is " + squareRoot(5)

 

 

SUB

sub subName zero or more comma separated parameter variable names

  'code for the sub goes in here

end sub

Description:

This statement defines a subroutine.  Zero or more parameters may be passed into the subroutine.  A subroutine cannot contain another subroutine definition, nor a function definition.

The CALL statement is used to access the SUBROUTINE and to pass values into it.  The values must be the same type as the SUB statement defines them to be.  So the following example:

  sub mySubName string$, number, string2$

is called like this:

  call mySubName "string value", 123, str$("321")

Local Variables

The variable names inside a subroutine are scoped locally, meaning that the value of any variable inside a subroutine is different from the value of a variable of the same name outside the subroutine.

Passing by Reference

Variables passed as arguments into subroutines are passed "by value" which means that a copy of the variable is passed into the subroutine.  The value of the variable is not changed in the main program if it is changed in the subroutine.  A variable may instead by passed "byref" which means that a reference to the actual variable is passed and a change in the value of this variable in the subroutine affects the value of the variable in the main program.

Global Variables and Devices

Variables declared with the GLOBAL statement are available in the main program and in subroutines and functions.

Arrays, structs and handles of files, DLLs and windows are global to a Just BASIC program, and visible inside a subroutine without needing to be passed in.

Special global status is given to certain default variables used for sizing, positioning, and coloring windows and controls.  These include variables WindowWidth, WindowHeight, UpperLeftX, UpperLeftY, ForegroundColor$, BackgroundColor$, ListboxColor$, TextboxColor$, ComboboxColor$, TexteditorColor$.  The value of these variables, as well as DefaultDir$ and com can be seen and modified in any subroutine/function.

Branch Labels

Branch labels are locally scoped.  Code inside a subroutine cannot see branch labels outside the subroutine, and code outside a subroutine cannot see branch labels inside any subroutine.

Ending a Subroutine:

The sub definition must end with the expression: end sub

Executing Subroutines

Be sure that a program doesn't accidentally flow into a subroutine.  A subroutine should only execute when it is called by command in the program.

wrong:

    for i = 1 to 10

        'do some stuff

    next i

 

    Sub MySub param1, param2

        'do some stuff

    End Sub

 

correct:

    for i = 1 to 10

        'do some stuff

    next i

 

    WAIT

    Sub MySub param1, param2

        'do some stuff

    End Sub

 

Example:

Usage:

'copy two files into one

fileOne$ = "first.txt"

fileTwo$ = "second.txt"

combined$ = "together.txt"

call mergeFiles fileOne$, fileTwo$, combined$

end

 

sub mergeFiles firstFile$, secondFile$, merged$

  open merged$ for output as #merged

  open firstFile$ for input as #first

    print #merged, input$(#first, lof(#first));

  close #first

  open secondFile$ for input as #second

    print #merged, input$(#second, lof(#second));

  close #second

  close #merged

end sub

Function

function functionName(zero or more parameter variable names)

  'code for the function goes in here

  functionName = returnValueExpression

end function

 

Description:

This statement defines a function.  The function can return a string value, or a numeric value. A function that returns a string value must have a name that ends with the "$" character.  A function that returns a numeric value must not include a "$" in its name.  Zero or more parameters may be passed into the function.  A function cannot contain another function definition, nor a subroutine definition.  Note that the opening parenthesis is actually part of the function name. Do not include a space between the name and the opening parenthesis, or the code generates an error. 

Right:

function functionName(var1, var2)

Wrong:

function functionName (var1, var2)

 

Returning a Value

To return a value from the function, assign the value to be returned to a variable of the same name as the function.  If no return value is specified, then numeric and string functions will return 0 and empty string respectively.

  functionName = returnValueExpression

 

Local Variables

The variable names inside a function are scoped locally, meaning that the value of any variable inside a function is different from the value of a variable of the same name outside the function.

 

Passing by Reference

Variables passed as arguments into functions are passed "by value" which means that a copy of the variable is passed into the function.  The value of the variable is not changed in the main program if it is changed in the function.  A variable may instead by passed "byref" which means that a reference to the actual variable is passed and a change in the value of this variable in the function changes the value of the variable in the main program.

 

Global Variables and Devices

Variables declared with the GLOBAL statement are available in the main program and in subroutines and functions.

 

Arrays, structs and handles of files, DLLs and windows are global to a Just BASIC program, and visible inside a function without needing to be passed in.

 

Special global status is given to certain default variables used for sizing, positioning, and coloring windows and controls.  These include variables WindowWidth, WindowHeight, UpperLeftX, UpperLeftY, ForegroundColor$, BackgroundColor$, ListboxColor$, TextboxColor$, ComboboxColor$, TexteditorColor$.  The value of these variables, as well as DefaultDir$ and com can be seen and modified in any subroutine/function.

 

 

Basic

REM

 

Pozwala wstawiać do programu komentarze objaśniające.

 

REM komentarz

' komentarz

 

    • komentarz    Dowolny tekst.

 

    • Komentarze sa ignorowane podczas pracy programu, z wyjątkiem gdy

      zawierają metapolecenia.

 

    • Komentarz może być wstawiony w linii po wykonywalnym poleceniu,

      jeśli jest poprzedzony apostrofową (') formą REM, lub jeśli REM jest

      poprzedzone przez dwukropek (:).

 

Zobacz także:    $STATIC, $DYNAMIC

 

Przykład:

    REM    To jest komentarz.

    '      To jest także komentarz.

    PRINT "Test1"       'To jest komentarz po poleceniu PRINT.

    PRINT "Test2" :  REM To jest także komentarz po poleceniu PRINT.

Test1
Test2

 

 

Typy danych

 

 

  Typy danych:  INTEGER,  LONG,  SINGLE,  DOUBLE,  STRING

 

Określa typ danych w poleceniach deklaratywnych lub listach parametrów:

 

  • INTEGER      16-bitowa zmienna całkowitoliczbowa.

  • LONG         32-bitowa zmienna całkowitoliczbowa. 

  • SINGLE       32-bitowa zmienna zmiennoprzecinkowa pojedynczej precyzji.

  • DOUBLE       64-bitowa zmienna zmiennoprzecinkowa podwójnej precyzji.

  • STRING * n%  Zmienna łańcuchowa o stałej długosci n% bajtów. 

  • STRING       Zmienna łańcuchowa o zmiennej długości

 

Zobacz także:   AS        Zestaw znaków QBasica      COMMON     DECLARE

                DEF FN         DIM, REDIM            FUNCTION

                SHARED, STATIC               SUB     TYPE

 

 

 

 

FOR ... NEXT

Powtarza blok poleceń wyszczególnioną liczbę razy.

 

FOR licznik = start TO end [STEP increment]

    [blok_poleceń]

NEXT [licznik [,licznik]...]

 

    • licznik          Zmienna numeryczna użyta jako licznik powtórzeń pętli.

    • start i end      Początkowa i końcowa wartość licznika.

    • increment        Wielkość, o jaką zwiększany jest licznik po każdym

                       przebiegu pętli.

 

Zobacz także:    DO...LOOP    EXIT    WHILE...WEND

 

Przykład:

    FOR i% = 1 TO 15

        PRINT i%

    NEXT i%

    FOR i% = 7 to -6 STEP -3

        PRINT i%

    NEXT i%

 

 GOSUB ... RETURN

 

Wychodzi do podprogramu i wraca z podprogramu.

 

GOSUB line1

.

.

.

RETURN [line2]

 

    • line1    Etykieta lub numer linii pierwszej linii podprogramu.

    • line2    Etykieta lub numer linii, dokąd ma nastąpić powrót

                    z podprogramu.

 

    • Jeśli nie umieścisz etykiety lub numeru linii w poleceniu RETURN,

      program podejmuje wykonywanie od polecenia następującego po GOSUB

      (przy wywoływaniu podprogramu), lub od miejsca, gdzie nastąpiło

      zdarzenie (przy obsłudze zdarzeń). Zob. słowo ON dla informacji

      o poleceniach obsługujących zdarzenia.

 

    • Polecenia SUB i CALL stanowią lepszą alternatywę dla podprogramów

      GOSUB.

 

 Zobacz także:   CALL    Słowo kluczowe ON    ON...GOSUB    SUB

 

Przykład:

    FOR i% = 1 TO 20

        GOSUB Kwadrat

    NEXT i%

    END

 

    Kwadrat:

    PRINT i%, i% * i%

    RETURN

 

 1             1

 2             4

 3             9

 4             16

 5             25

 6             36

 7             49

 8             64

 9             81

 10            100

 11            121

 12            144

 13            169

 14            196

 15            225

 16            256

 17            289

 18            324

 19            361

 20            400

 

IF warunek1 THEN

    [blok_poleceń-1]

[ELSEIF warunek2 THEN

    [blok_poleceń-2]]...

[ELSE

    [blok_poleceń-n]]

END IF

 

IF warunek THEN polecenia [ELSE polecenia]

 

    • warunek1          Jakieś wyrażenie, które może być zinterpretowane

      warunek2          jako prawda (nie-zero) lub fałsz (zero)

 

    • blok_poleceń-1    Jedno lub więcej poleceń, w jednej lub więcej linii.

      blok_poleceń-2

      blok_poleceń-n

 

    • polecenia         Jedno lub więcej poleceń, oddzielonych dwukropkami.

 

 

 Zobacz także:   ON...GOSUB   ON...GOTO    SELECT CASE

 

Przykład:

    INPUT "1 czy 2? ", i%

    IF i% = 1 OR i% = 2 THEN

        PRINT "OK"

    ELSE

        PRINT "Poza zakresem"

    END IF

 

1 czy 2? 1
OK
1 czy 2? 2
OK
1 czy 2? 3
Poza zakresem

 INPUT,   LINE  INPUT

 

INPUT odczytuje wprowadzenie z klawiatury lub z pliku. LINE INPUT czyta

linię do 255 znaków z klawiatury lub z pliku.

 

INPUT [;] ["komunikat"{; | ,}] lista_zmiennych

LINE INPUT [;] ["komunikat";] zmienna$

INPUT #filenumber%, lista_zmiennych

LINE INPUT #numer_pliku%, zmienna$

 

    komunikat        Opcjonalny ciąg znaków, który jest wyświetlany

                      zanim użytkownik wprowadzi dane. Średnik po komuni-

                      kacie dodaje do niego znak zapytania.

 

   • lista_zmiennych  Jedna lub więcej zmiennych oddzielonych przecinkami,

                      w których są przechowywane dane wprowadzane z klawia-

                      tury lub wczytywane z pliku. Nazwy zmiennych mogą

                      składać się z maksimum 40 znaków i muszą zaczynać się

                      od litery. Akceptowane znaki to A-Z, 0-9, i kropka (.).

 

   • zmienna$         Przechowuje linię znaków wprowadzoną z klawiatury

                      albo odczytaną z pliku.

 

   • numer_pliku%     Numer otwartego pliku.

 

   • INPUT używa przecinka jako separatora pomiędzy wprowadzeniami.

     LINE INPUT czyta wszystkie znaki do znaku końca wiersza.

 

   • Dla wpisu z klawiatury - średnik bezpośrednio po INPUT utrzymuje

     kursor w tej samej linii po naciśnięciu Enter przez użytkownika.

 

Zobacz także:    INKEY$    INPUT$    Tryby otwarcia plików

   

Przykład:

    CLS

    OPEN "LIST" FOR OUTPUT AS #1

    DO

        INPUT "   IMIE:       ", Imie$  'Czyta wpisy z klawiatury.

        INPUT "   WIEK:       ", Wiek$

        WRITE #1, Imie$, Wiek$

        INPUT "Dodac nowy wpis"; R$

    LOOP WHILE UCASE$(R$) = "T"

    CLOSE #1

    'zwrotne echo z pliku

    OPEN "LIST" FOR INPUT AS #1

    CLS

    PRINT "Zapisy w pliku:": PRINT

    DO WHILE NOT EOF(1)

        LINE INPUT #1, REC$  'Czyta zapisy z pliku.

        PRINT REC$           'Wypisuje je na ekranie.

    LOOP

    CLOSE #1

    KILL "LIST"

 

Zapisy w pliku:

"ADAM","30"
"BASIA","20"

 INPUT$

 

Zwraca łańcuch znaków odczytany z określonego pliku  lub z klawiatury.

 

INPUT$(n[,[#]numer_pliku%])

 

    • n               Liczba znaków (bajtów) do odczytania.

 

    • numer_pliku%    Numer otwartego pliku. Jeśli numer pliku jest

                      opuszczony, INPUT$ czyta z klawiatury.

 

Zobacz także:    INPUT, LINE INPUT

 

Przykład:

    OPEN "TEST.DAT" FOR OUTPUT AS #1

    PRINT #1, "The text"

    CLOSE

    OPEN "TEST.DAT" FOR INPUT AS #1

    PRINT INPUT$(3, 1)        'Wypisuje pierwsze 3 znaki.

    CLOSE

 

 

 PRINT,  LPRINT

 

PRINT wypisuje dane na ekran lub do pliku.

LPRINT drukuje dane na drukarce LPT1.

 

PRINT [#numer_pliku%,] [lista_wyrażeń] [{; | ,}]

LPRINT [lista_wyrażeń] [{; | ,}]

 

    • numer_pliku%      Numer otwatego pliku. Jesli nie określisz numeru

                        pliku, PRINT pisze na ekran.

 

    • lista_wyrażeń     Lista jednego lub więcej wyrażeń numerycznych

                        lub łańcuchowych do wypisania.

 

    • {; | ,}           Określa, gdzie rozpocznie się następny wpis:

                          ; oznacza drukowanie bezpośrednio po ostatniej

                            wartości.

                          , oznacza drukowanie od początku następnej strefy

                            drukowania. Strefy drukowania mają szerokość

                            14 znaków.

 

Zobacz także:    PRINT USING, LPRINT USING    WIDTH    WRITE

 

Przykład:

    OPEN "TEST.DAT" FOR OUTPUT AS #1

    PRINT #1, USING "##.###  "; 12.12345

    CLOSE

    OPEN "TEST.DAT" FOR INPUT AS #1

    INPUT #1, a$

    PRINT a$

    LPRINT "To jest linia"; 1

    LPRINT "To jest linia",

    LPRINT 2

 

12.123

 PRINT  USING,    LPRINT  USING

 

PRINT USING wypisuje tekst sformatowany na ekran lub do pliku.

LPRINT USING drukuje tekst sformatowany na drukarce LPT1.

 

PRINT [#numer_pliku%,] USING łańcuch_formatujący$; lista_wyrażeń [{; | ,}]

LPRINT USING łańcuch_formatujący$; lista_wyrażeń [{; | ,}]

 

    numer_pliku%     Numer otwartego pliku sekwencyjnego.

 

    • łańcuch_formatujący$;    Wyrażenie łańcuchowe zawierające jeden

                       lub wiecej znaków formatujących.

 

    • lista_wyrażeń    Lista jednego lub więcej wyrażeń numerycznych lub

                       łańcuchowych do wypisania, oddzielonych perzecinkami,

                       średnikami, apcjami lub tabulatorami.

 

    • {; | ,}          Określa, gdzie rozpocznie się następny wpis:

                          ; oznacza drukowanie bezpośrednio po ostatniej

                            wartości.

                          , oznacza drukowanie od początku następnej strefy

                            drukowania. Strefy drukowania mają szerokość

                            14 znaków.

 

Zobacz także:    PRINT, LPRINT    WIDTH

 

Przykład:

    a = 123.4567

    PRINT USING "###.##"; a

    LPRINT USING "+###.####"; a

    a$ = "ABCDEFG"

    PRINT USING "!"; a$

    LPRINT USING "\ \"; a$

 

 

 

 

123.46

A

 

 

 

 

                    Znaki, które formatują wyrażenie numeryczne

 

 #    Pozycja cyfry.                   ¦ -     Umieszczony po cyfrze,

 .    Pozycja kropki dziesiętnej.      ¦       drukuje wiodący minus

 ,    Umieszczony na lewo od kropki    ¦       dla liczb ujemnych.

      dziesiętnej, drukuje przecinki   ¦ $$    Drukuje wiodący $.

      co każde trzy cyfry.             ¦ **    Wypełnia gwiazdkami (*)

 +    Pozycja znaku liczby   .         ¦       wiodace spacje.

^^^^  Drukuje w postaci wykładniczej   ¦ **$   Kombinacja ** and $$.

 

                 Znaki używane do formatowania wyrażenia łańcuchowego

 

 &    Drukuje cały łańcuch.            ¦ \ \   Drukuje pierwszych n znaków,

 !    Drukuje tylko pierwszy znak      ¦       gdzie n jest liczbą spacji

      łańcucha.                        ¦       miedzy \ \ plus 2.

 

                        Znaki używane do druku literałów

 

 _    Drukuje następny znak            ¦       Każdy znak nie zamieszczony

      formatujacy jako literał         ¦       w tej tabeli jest drukowany

                                       ¦       jako literał.

 

 SPC

 

Wstawia określoną liczbę spacji w poleceniach PRINT i LPRINT.

 

SPC(n%)

 

    • n%    Liczba spacji do wstawienia; wartość z zakresu 0 do 32767.

 

Zobacz także:    PRINT, LPRINT    PRINT USING, LPRINT USING

                 SPACE$           TAB

Przykład:

    PRINT "Tekst1"; SPC(10); "Tekst2"

 

 

Tekst1          Tekst2

 

 

TAB

 

Przesuwa kursor na określoną pozycję drukowania.

 

TAB(kolumna%)

 

    • kolumna%    Numer kolumny nowej pozycji drukowania.

 

Przykład:

    PRINT TAB(25); "Tekst"

 

Zobacz także:    PRINT, LPRINT    PRINT USING, LPRINT USING

                 SPC    SPACE$

 

 

 

                         Tekst