BASIC Programming/Printable version


BASIC Programming

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/BASIC_Programming

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.

Beginning BASIC/Your First Program

Introduction Edit

Many texts written about programming languages show you a sample program at the beginning of the lesson to help get your feet wet. That is, to become familiar with the syntax and layout of that language. This book is no exception. This sample program will display the text "Hello, world!" to your screen.

Program Examples Edit

Example One (FreeBASIC)

10 CLS
20 INPUT " Enter Your Name " X
30 PRINT X = " YOUR NAME"
40 END

.

Explanation Edit

  1. CLS stands for 'Clear Screen' and erases everything in the Command Prompt.
  2. PRINT displays everything in between the quotations.
  3. INPUT gives input and tell what to do.
  4. END marks the end of the program (explained later in functions.)

External Links Edit

Wikipedia's article on Hello World

  Index Next: Beginning BASIC/PRINT, CLS, and END


Beginning BASIC/PRINT, CLS, and END

BASIC Programming > Beginning BASIC > Your First Program


Introduction Edit

In the previous code example, we wrote your first BASIC program. In it, you saw examples of PRINT, CLS, and END commands. Their roles in the program may or may not have been apparent at the time, but, as they're so vital to the BASIC language, they will be discussed here.


10 CLS
20 PRINT "Hello, world!"
30 PRINT "I'm making the sample program clear and understandable."
40 PRINT "This text is being printed via the PRINT command."
50 PRINT "On the next line, I'll use CLS, which will clear everything I just printed, so you won't even see the preceding text."
55 PRINT "Also, you can't give CLS a line to PRINT; it won't actually do anything"
60 CLS "These words actually do nothing; they do not PRINT or anything."
70 PRINT "Finally, on line 80, I'll use END, which will keep me from reaching line 90."
80 END "Like CLS, putting a string here does nothing; it does not PRINT or anything."
90 PRINT "this is not really my answer."

Output Edit

(CLS)
Hello, world!"
I'm making the sample program clear and understandable."
This text is being printed via the PRINT command."
On the next line, I'll use CLS, which will clear everything I just printed, so you won't even see the preceding text."
Also, you can't give CLS a line to PRINT; it won't actually do anything"
(CLS)
Finally, on line 80, I'll use END, which will keep me from reaching line 90."
(END)

-Program end-

Discussion Edit

From that example, it's fairly easy to deduce what each command does.

CLS
An abbreviation that stands for the words CLear Screen. In the above program, when you used CLS on line 60, all of the words that were printed to the screen were wiped away.
PRINT
Writes to the screen. There are commands for printing to other things, like a printer, but that's to be discussed later. Each new PRINT command will start printing on a new line. To insert a blank line, don't specify a string to print. The syntax for "PRINT" is: PRINT "[whatever you want to be printed here]"
END
It stops the program at that line; that is, anything that's added after that won't show. That's why the PRINT command on line 90 didn't print anything. The END command can be included in control structures to end the program if a condition is met. This will be discussed with control structures.


What is happening?

  1. Line 10 the display is cleared.
  2. Lines 20 through 50 print text to the screen.
  3. Line 60 clears the display.
  4. Line 70 shows the message you should see after you run this program.
  5. Line 80 ends the program.
  6. Line 90 shows that an END statement stops the program. No instruction following an END statement is executed.

Given the state of computer speed today you should not see the paragraph displayed by lines 20 through 50, it should be cleared by the CLS statement on Line 60 before you have a chance to see it. If you slow the program down you can see the program write the message to the screen. Line 70 is then written to the screen/display then Line 80 stops everything. Line 90 never, ever runs.


Previous: Beginning BASIC/Your First Program Index Next: Beginning BASIC/Variables and Data Types


Beginning BASIC/Variables and Data Types

Variables allow you to store and change information. Below is an example how to use variables.

Example Code for Variables Edit

Example 1 (qBasic)

CLS
ASTRING$ = "Hello World"
ANUMBER% = 10
PRINT ASTRING$
PRINT ANUMBER%

Example 1.2 (freeBasic)

Cls
Dim aString As String
Dim anInteger As Integer
aString = "John Doe"
anInteger = 42
Print aString
Print anInteger
Sleep
End

Output Edit

Example 1

Hello World
10

In Basic, a string variable ends in a $, and whole number variables, known as integers, end with a %.

Example 2

John Doe
42

If you use Dim varName As DataType to declare variables, you do not need to use a suffix.

Arrays Edit

An array is a collection of values.

Cls
Dim aNames(3) as String
aNames(1)="John Doe"
aNames(2)="Jane Doe"
PRINT aNames(1)
PRINT aNames(2)


Beginning BASIC/User Input

Introduction Edit

Read the Variables and Data Types article before reading this one.

User Input is one of the most important aspects of programming concepts. Every program should have some sort of user interaction, from getting a character's name for a game to asking for a password to log into a database. This article will teach the basics of user input in the BASIC Programming Language. Please note that the following code may vary from compiler to compiler. (FreeBASIC Users: Do not use line numbers).

Code Edit

  1. you can copy it from here, hashtags do not do anything, it's a reminder.

Example 1 (qBasic)

CLS
10 PRINT "what is your name?"
20 INPUT "...(Enter Your Name)...", a$
30 PRINT
40 PRINT "hello, "; a$; ", I am your computer, nice to meet you."
60 END

Example 2 (freeBasic)

10 Dim userInput As String
20 Input "What is your name?", userInput
30 Print
40 Print "Hello, " ; userInput ; "! I am your computer, it's nice to meet you."
50 Sleep
60 End

Explanation Edit

Output

What is your name?
...(Enter Your Name)...

Hello, yourName, I am your computer, nice to meet you.

10: Dim userInput declares the variable userInput. As String tells the compiler that userInput is a string (A collection of pure text, can include numbers and symbols, but is considered text).
20: Input "What is your name?" prompts the user for their name. userInput OR a$ tells the compiler to store the answer in the variable in userInput or a$.
30: Makes a blank line.
40: A normal Print statement, ; tells the compiler not to skip to the next line.
50: Sleep makes the program wait for the user to press a key.
60: The ending to all BASIC programs, signifies a termination of the program.


Previous: [[../../Beginning BASIC/Variables and Data Types|Variables and Data Types]] Main: BASIC Programming Next: [[../../Beginning BASIC/Documentation|Documentation]]


Beginning BASIC/Documentation

Introduction Edit

In Basic, code is documented in one of two ways:

  • a remark, indicated by the REM statement
  • a full-line comment introduced by an apostrophe: (')

Either of these two methods will result in treating the rest of the line as a comment. The interpreter will discard the rest of the line.

As with most forms of code documentation, it needs to be used as programs grow larger and to help identify the purpose of a given section of code. It is unnecessary to document every individual line, but should give enough information such as the purpose of a given function or why a certain statement may be needed.

Code Edit

first example (qBasic)
CLS
10 PRINT "Hello World!"
20 REM This code will display Hello World! to the display.
30 END
second example (freeBasic)
print "Hello World!"
'This code will display Hello World! on the screen
sleep
end

Explanation Edit

This will allow you to create a Remark statement that will not be visible to the user, but will be visible when the code is reviewed.


Previous: [[../../Beginning BASIC/Variables and Data Types|Variables and Data Types]] Main: BASIC Programming Next: [[../../Beginning BASIC/Documentation|Documentation]]


Beginning BASIC/Control Structures/IF...THEN...ELSEIF...ELSE

The IF...THEN...ELSEIF...ELSE control statement allows identifying if a certain condition is true, and executes a block of code if it is the case.

10 CLS
20 IF number<0 THEN
30   PRINT "Number is negative"
40 ELSEIF number>0 THEN
50   PRINT "Number is positive"
60 ELSE
70   PRINT "Number is zero"
80 END IF

In some implementations of BASIC (but permitted by most versions), the IF statement may need to be contained in one line. However, ELSEIF may not be available in this case, and there is no need for an explicit END IF:

10 CLS
20 IF number<0 THEN PRINT "Number is negative" ELSE PRINT "Number is non-negative"

This carries over into some implementations of BASIC where if the "IF...THEN" statement is followed by code on the same line then it is fully contained. That is, the compiler assumes the lines ends with "ENDIF", even if it not stated. This is important when dealing with nested "IF...THEN" clauses:

10 CLS
20 IF X<2 THEN
30   IF 2<3 THEN PRINT "This is printed if X is 1"
40 ELSE
50   IF 3<4 THEN PRINT "This is printed if X is 3"
60 END IF

The ELSE clause, while following the "IF 2<3" statement, is associated with the "IF X<2" statement, because the "IF 2<3" statement has a PRINT statement on the same line.

Let me give some more examples of "if-then-else" programs:

Q1)Input the age of a person and check whether he/she is voter or not?

Ans1) 10 CLS 20 INPUT AGE 30 IF AGE>=18 THEN 40 PRINT "VOTER" 50 ELSE 60 PRINT "NON VOTER" 70 END IF 80 END

Q2)Input the age of a person to check if he/she is a senior citizen or not a senior citizen?

Ans2) 10 CLS 20 INPUT AGE 30 IF AGE>=60 THEN 40 PRINT "SENIOR CITIZEN" 50 ELSE 60 PRINT "NOT A SENIOR CITIZEN" 70 END IF 80 END


Beginning BASIC/Control Structures/WHILE...WEND

 INPUT "What is your name"; UserName$
 PRINT "Hello "; UserName$
 DO 
   INPUT "How many stars do you want"; NumStars
   Stars$ = ""
   Stars$ = REPEAT$("*", NumStars) '<-ANSI BASIC
   'Stars$ = STRING$(NumStars, "*") '<-MS BASIC
   PRINT Stars$
   DO
     INPUT "Do you want more stars"; Answer$
   LOOP UNTIL Answer$ <> ""
 LOOP WHILE UCASE$(LEFT$(Answer$, 1)) = "Y"
 PRINT "Goodbye ";
 FOR A = 1 TO 200
   PRINT UserName$; " ";
 NEXT A
 PRINT


Beginning BASIC/Control Structures/FOR...NEXT

The FOR...NEXT loop is a form of flow control that places focus on a single counter.

The basic syntax is simple - a variable is given a starting value and ending value, and it increments on each pass of the loop:

FOR i = 1 TO 10
NEXT

A more advanced loop includes the STEP parameter, which specified the value at which a variable is incremented. It can be negative to have the loop decrease the variable instead of increasing it, and may even be fractional. An example of a reverse counting loop is as follows:

FOR i = 10 TO 1 STEP -1
NEXT

The FOR loop terminates when the variable passes the final value in the loop. This is checked by determining if it is greater than the second parameter (or less than if STEP is negative.)

If desired, you can place variables within the start and end parameters instead of constant numbers.


Beginning BASIC/Control Structures/DO...LOOP

In the last chapter we learned about inputing data to the program. Well now you'll be learning how to repeat a function over and over again. Remember anything to the right of an apostrophe (') are comments in one version of BASIC, and should be removed, or replaced with a different kind of REMARK, if they cause problems.

CLS 'Clears screen for user

DO 'Starts the Looping process, anything between this and the LOOP command will be repeated.
  PRINT "You will get this message over and over." 'Displays the message "You will get this message over and over."
LOOP ' Shows where objects should stop being looped.

This loop will continue forever, unless interrupted by the operating system. If you wanted to have a condition where the loop ends, you can put a WHILE or UNTIL keyword after LOOP.


Beginning BASIC/Control Structures/GOTO

The GOTO statement in BASIC is used to jump to a specific location or label within the source code; it may take either a line number (which appears at the beginning of a line) or a label (which is a word that ends in a colon).

This statement was originally essential for programming in Basic; the older interpreters only allowed IF statements to run on one line and did not have more advanced handling of FOR or WHILE loops. Under modern versions of Basic, you will generally see GOTO used only to return to the top of a main loop. In all other cases, usage of GOTO has been deprecated in favor of other statements.

GOSUB Edit

The Gosub statement is a variation of the Goto statement. When used, it jumps to a specific location within the program, and allows the next RETURN statement to head back to the point just after the GOSUB call.

This statement must be paired with a matching return statement. Under modern versions of Basic, GOSUB uses a stack of locations that may be filled up, resulting in a stack overflow.


Random Number Generation

One useful thing for games is random numbers. This is a sequence of numbers that appears randomly distributed, so they can be used to simulate things like shuffling a deck of cards or producing different behaviours every time a program runs.

Random numbers in BASIC are generated by the RND function. This returns a number between 0 and 1. For example:

PRINT "Wikibooks' coolness quotient: ", RND, "%"

You will get "Wikibooks' coolness quotient: .7055475%".

That result looks random. Run it again and you get the same value! That makes a game boring. This is the purpose of seeding, which is normally accomplished with the RANDOMIZE statement. In modern dialects, this can be tied to the clock using the TIMER keyword:

RANDOMIZE TIMER
PRINT "Wikibooks' coolness quotient: ", RND, "%"

which will print "Wikibooks' coolness quotient: .8532526%" and another time will print "Wikibooks' coolness quotient: .3582422%". Better, right?

But decimal numbers are not always useful. If you want a whole number, you must get a random number and then convert it to a whole number. Normally you want that number to be between two limits, say 0 and 100. One solution is to take the number, multiply by the maximum desired value, add half to round it, and then take the whole number part. Some slight variation on the following code is very common:

PER = INT(RND() * 99 + 0.5)

Modern dialects like QBASIC offer more control. We can state the variable is an integer, and BASIC will force it to that format and slightly simplify the code:

RANDOMIZE TIMER
DIM PER AS INTEGER
PER = RND * 100 + 0.5
PRINT "Wikibooks' coolness quotient: ", PER, "%"

which will print "Wikibooks' coolness quotient: 85%".


Subroutines and Functions

Introduction Edit

Functions and Subroutines are lines of code that you use more than once. The purpose of functions and subroutines is to save time and space by just calling a function/subroutine. There is hardly a difference between the two, except that a function returns a value, where a subroutine just repeats lines of code (A function is not always used more than once).

An example of a function, say you are making a program that calculates sales tax. The function would ask for a subtotal, take that number and multiply it by 1.07 (If sales tax is 7%, the 1 is because you are adding onto the subtotal to make a total, not finding the sales tax itself). The function would take the new total and give it back to the program.

A subroutine would be code that is reused, like a shop in a game. Every time the user goes to the shop, the program will go back to the Shops Subroutine, and if the user bought an item, it would call a "Buy Item" function.

Parameters Edit

Parameters are used in functions and subroutines. They pass data to be used with the function/parameter. For use with our two examples:

Function Parameters) The Subtotal passed to the function is a parameter.
Subroutine Parameters) The player's amount of gold could be sent to the subroutine so the shop
knows how much money the player can spend.

There are two different ways to send parameters: by the value or by reference. By Value means that the function can not actually change the data outside of the function, but can use its data to manipulate other data that is returned. By Value is like making a carbon copy of a paper and then editing the carbon copy. By Reference sends the actual argument (parameter) to the function/subroutine, which is like editing the original copy of the paper. By Value is written as ByVal and By Reference is written as ByRef.

Functions Edit

Ignore the line numbers; they are used for explaining the code.
Example 1 (FreeBASIC)

1. Declare Function salesTax(ByVal subTotal As Double) As Double
2. Dim SubTotal2 As Double
3. Dim Total2 As Double
4. SubTotal2 = 10.00
5. Total2 = salesTax(SubTotal2)
6. Print "Subtotal:" ; SubTotal2
7. Print "Total:" ; Total2
8. Sleep
9. End
10.
11. Function salesTax(ByVal subTotal As Double) As Double
12.   Dim Total As Double
13.   Total = subTotal*1.07
14.   return Total
15. End Function



1. This line is the function's prototype. Functions must be declared as a prototype before they are used, and must be defined after the end (of the program) statement. Function means that the following is related to functions. salesTax is the function identifier or its name, and in parentheses are the parameters (If you have more than one parameter, separate them with a comma). After the parentheses tells what Data Type the function returns. Double is a Data Type that signifies a number with decimals (00.00).
2. Create the SubTotal2 variable (Parameters can not be the same as existing identifiers).
3. Create the Total2 variable.
4. Define SubTotal2 with the value 10.00 (Change this to get new outputs)
5. Define Total2 by passing SubTotal2 as an argument(parameter) to the function salesTax (The value of Total2 will be what the function returns).
6. Display the subtotal.
7. Display the total.
8. Wait for the user to press enter (So you can read the output with out it flashing away in a second).
9. End the program (In a sense. You can't interact with the user past the End point)
10. Blank Line, easier to read the code.
11. This is where you define the function, earlier you declared the function.
12. Create the variable Total (This variable can only be used in the function, because it was defined in the function. This is called the variable scope).
13. You do not need to declare subTotal, because it was defined as a parameter, this math finds the total with sales tax and assigns it to the variable Total.
14. This is what line 5 receives, the function shoots out the variable Total.
15. Ends the function definition.

GOSUB ... RETURN Statement

Purpose:

To branch to, and return from, a subroutine. Syntax:

GOSUB line number
.
.
.
RETURN [line number]

Comments:

line number is the first line number of the subroutine.

A subroutine may be called any number of times in a program, and a subroutine may be called from within another subroutine. Such nesting of subroutines is limited only by available memory.

A RETURN statement in a subroutine causes GW-BASIC to return to the statement following the most recent GOSUB statement. A subroutine can contain more than one RETURN statement, should logic dictate a RETURN at different points in the subroutine.

Subroutines can appear anywhere in the program, but must be readily distinguishable from the main program.

To prevent inadvertent entry, precede the subroutine by a STOP, END, or GOTO statement to direct program control around the subroutine. Examples:

10 GOSUB 40
20 PRINT "BACK FROM SUBROUTINE"
30 END
40 PRINT "SUBROUTINE";
50 PRINT " IN";
60 PRINT " PROGRESS"
70 RETURN
RUN
SUBROUTINE IN PROGRESS
BACK FROM SUBROUTINE

The END statement in line 30 prevents re-execution of the subroutine.

Conclusion Edit

Subroutines do not return any values, while functions return values. Subroutines are also allowed to change values of the parameters while functions are supposed to maintain.


External Libraries

// Code your testbench here // or browse Examples

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="index.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <script src="index.js"></script>
  </body>
</html>