Friday, November 21, 2014

QBasic tips & tricks

QBasic, Microsoft's version of the BASIC programming language, isn't widely used by any stretch of the imagination.  However, some people still use it, and it can come in handy for designing simple programs (especially if you have a compiler).  Below are some tips and tricks for getting more done with QBasic.

Microsoft's QBasic editor is smarter than a normal text editor, so you can save some time by letting it do a lot of the formatting work for you.  For example, if you type "10 print a$:input c$:goto 20" you'll see the following line when you press <Enter>:

10 PRINT a$ : INPUT c$ : GOTO 20

Another shortcut is to use a question mark instead of typing out PRINT.  QBasic will translate a question mark (?) as PRINT, as long as you don't put it in quotation marks.  So typing "?number" would become "PRINT number".  (In this example, QBasic would assume "number" is a variable.)

When using the INPUT command, QBasic typically inserts an end-of-line character after the user's input, so anything you want the program to print will automatically start on the next line.  But if you use a semi-colon with INPUT, you can bypass the end-of-line insertion and keep the program on the same line.  So if you wrote a program that consisted of these two lines:

INPUT ; a$
PRINT a$

QBasic would print whatever the user typed in right next to where they typed it, rather than skip to the next line.  If you're using a prompt with INPUT, however, this tip won't work; QBasic will still skip to the next line, even with the semi-colon present.

If you don't use subroutines, you are probably writing a lot of redundant code.  QBasic lets you call subroutines and then return to where you were in the program, so that commands that you would run often can just be typed in once and then accessed as many times as necessary.

Subroutines work well for tasks that must be repeated over and over again without any change.  As an example, if you were writing a self-test program to study for an exam, you could write one subroutine that would get the input from the user, and another subroutine that would take the user's answer and compare it to the correct answer to see if the user was right or wrong.  That way, for each unique question you would only have to give the program the question and the correct answer, and the subroutines could do the rest.  To call a subroutine, use the syntax "GOSUB <line number>", and then putting "RETURN" at the end of the subroutine will give control back to the line that called it.

(Originally published on Helium.com, May 2010)

No comments:

Post a Comment