Lesson 2: Introducing Variables

Variables are containers used in programming to hold values. The values can be numerical, character based such as letters, or a combination of both. Once a variable has been set with a value that value can be called upon later on in the program. To see an example of this start a new program in the IDE and type the following program in.

PRINT "Enter your name:"
INPUT user$
PRINT "Hello " + user$

Go ahead and run the code now (remember you can use F5 as a shortcut to execute your code). When the ? question mark appears on the output screen type in your first name and then press the ENTER key. The output of your program should be similar to Figure 1 below.

Figure 1: The program's output screen

The first line of code containing the PRINT command should look familiar from lesson 1. It simply prints the literal string "Enter your name:" to the output screen. The second line of code however uses a new command statement called INPUT. The INPUT command can be used to gather information from a variety of sources. In this case we are instructing the INPUT command to gather information from the keyboard and then store that information into a variable called user$.

The variable user$ has been defined as a variable that can hold characters by the use of the dollar sign ($) after the variable name. When the computer encounters user$ it sees that a variable called user needs to be created. Furthermore, because of the $ at the end of the variable it knows the information must be stored in memory as a string of characters. The computer then sets aside room in the computer's RAM to hold this information. After the user has typed in their name that string of characters is then saved to the RAM set aside by the computer. A variable created using a $ is called a string variable because it is meant to hold a string of characters in memory. We say that the variable user has been declared as a string type variable.

The third line of code then prints the literal string "Hello " and then adds the string variable's information afterwards. Since the text in quotes is a literal string and the variable has been declared as a string we can add (+) these two objects together since they are the same type ... strings in this case. When we do this the information that was typed in and stored in line 2 is now called upon and used to finish the PRINT statement in line 3.

The act of adding two or more strings together is known as concatenation in the programming world. Seriously, I'm not making that up.

Variable Types

There are several different types of variables that can be declared in all programming languages. The type of variable you choose to use will depend on the type of information you wish to store inside of it.

INTEGER ( % )

An integer type variable can hold any whole number value in the range of -32768 to +32767. Integers are the fastest type of variable that can be processed in most languages and should be used as much as possible for numbers falling within the valid range. An integer variable is created by adding a percent sign (%) at the end of the variable name.

Example: PlayerScore%

LONG INTEGER ( & )

A long integer type variable can hold any whole number value in the range of -2,147,483,648 to +2,147,483,647. Long integers are also processed very quickly by QB64 and should be used as much as possible for integer values falling outside of the valid range of standard integers. A long integer variable is created by adding an ampersand (&) at the end of the variable name.

Example: SecondsElapsed&

SINGLE PRECISION ( ! )

A single precision type variable can hold any real number value in the range of 2.802597E-45 to 3.402823E+38. Think of single precision values like the values you would find using a standard calculator. Single precision numbers can have up to 7 digits after the decimal point. After that engineering notation is used to display an approximate value. Single precision values are handled slowly by programming languages due to their complexity and should only be used if necessary. A single precision variable is created by adding an exclamation point (!) at the end of the variable name.

Example: ValueofPI!

DOUBLE PRECISION ( # )

A double precision type variable can hold any real number value in the range 4.490656458412465E-324 to 1.797693134862310E+308. We are talking about counting the grains of sand on all the beaches in the world or the numbers of stars and planets contained in the universe. Truly HUGE values with very precise decimal point accuracy. Double precision numbers can have up to 15 digits after the decimal point. After that engineering notation is used to display an approximate value. A double precision variable is created by adding a pound sign (#) at the end of the variable name.

Example: PicoCycles#

STRING ( $ )

A string type variable can hold any valid computer generated characters in the range of zero characters (also called a null string) up to 2,147,483,647 characters. That's two gigabytes worth of characters in one variable, enough to hold a novel such as War and Peace. A string variable is created by adding a dollar sign ($) at the end of the variable name.

Example: PlayerName$

There are a few more variable types that can be created within QB64 but these are the most common found throughout all programming languages and will do just fine for now. Later in the course we'll discuss other types as a need arises to use them. A complete listing of all variable types supported by QB64 can be viewed here.

Variable Naming

There are a few rules that need to be followed when creating variable names in QB64. Most of these rules are also universal amongst other programming languages as well.

- Variable names can only begin with a letter of the alphabet. For example OneTime$ is a valid variable name but 1Time$ would be considered an invalid variable name.

- Variable names can only contain combinations of upper and lower case letters, numbers, and underscore (_) characters. Examples of valid variable names would be First1%, User_Name$ and My__Variable!

- Variable names can't be named the same as a QB64 command statement, otherwise known as a reserved word. Examples of invalid variable names would be Print$ and Input% since PRINT and INPUT are QB64 command names, or reserved words.

- Although not a rule, it is good practice to name your variables in such a way that they give meaning to the information that they are intended to hold. For example, a variable that holds the user's current score might be named PlayerScore& or a variable that holds the current tax rate might be named as TaxRate!

- Another good practice is to declare variables in a program before they are used. We'll discuss this in more detail later in the course.

Example Code

The best way to see variables in action is to write some code. Let's start by modifying the program you typed in at the beginning of this lesson. Once a variable has some information stored within it you can use that information over and over. Furthermore, you can change a variable's contents at any time you wish. Make the following changes to your code and then execute the program to see it in action.

PRINT "Enter your name:"
INPUT response$
PRINT "Hello " + response$
PRINT "How is " + response$ + " feeling today?"
INPUT response$
PRINT "What a coincidence, I'm feeling kind of " + response$ + " myself."

As you can see in lines 3 and 4 of the code we used the value stored in response$ from line 2. Once a variable has been set with a value that value can be called upon numerous times. In line 5 the program once again sets response$ with a new value. Variables can have their values changed at any time. The use of a variable to hold different information throughout a program is quite common.

Let's create a very simple game that keeps track of how many math questions the player gets correct. We'll use a variable called score% to keep track of the player's score throughout the game. Each time the player correctly answers a question the program will increase the score by one. At the end of the game the player's skill level will be judged by the score they received.

( This code can be found at .\tutorial\Lesson2\MathGame.bas )

score% = 0
PRINT "Hello Player! What is your name?"
INPUT PlayerName$
PRINT
PRINT
"Welcome " + PlayerName$ + "!"
PRINT "Please answer the following math questions."
PRINT "A score of 5 is perfect."
PRINT "What is the result of 1 + 1"
INPUT answer%
IF answer% = 2 THEN score% = score% + 1
PRINT "What does 3 times 4 equal"
INPUT answer%
IF answer% = 12 THEN score% = score% + 1
PRINT "What's the answer to 81 divided by 9"
INPUT answer%
IF answer% = 9 THEN score% = score% + 1
PRINT "What does 7 times 8 plus 10 equal"
INPUT answer%
IF answer% = 66 THEN score% = score% + 1
PRINT "What is the answer to the ultimate question of life, the universe, and everything."
INPUT answer%
IF answer% = 42 THEN score% = score% + 1
PRINT "Your score:"; score%
PRINT "You have the skills of ";
IF score% = 0 THEN PRINT "pond scum"
IF score% = 1 THEN PRINT "a counting horse"
IF score% = 2 THEN PRINT "a genius monkey"
IF score% = 3 THEN PRINT "an above average dolphin"
IF score% = 4 THEN PRINT "a grade school human"
IF score% = 5 THEN PRINT "the Deep Thought computer!"
PRINT "Thank you for playing " + PlayerName$

Three variables are used throughout this simple math game ... PlayerName$, score%, and answer%. PlayerName has been declared as a string type since it will hold the player's name which is alphabetical information. The variable score has been declared as an integer type because it will act as a counter, increasing by 1 each time the player gets an answer correct. The variable answer has also been declared as an integer type because the responses from the player are to be numeric in value.

Don't worry about the new commands you see in the program, we'll eventually get to them. The nice thing about QB64 however is that even with the new commands introduced you should still be able to read this code with little trouble. Take this line for example:

IF score% = 0 THEN PRINT "pond scum"

The line of code reads exactly like an English language statement and describes exactly what it does, "If the value in the variable score is zero then print pond scum to the screen".

Notice also these statements seen throughout the program:

score% = score% + 1

This effectively adds the value of 1 to the current value contained in score%, "take the value currently contained in score%, add 1 to it, and then place that new value back into score%". This is a simple counter construct and is used quite often in programming.

Math 101

Variables are used for much more than just holding a value in memory for us. They can also be used to solve math problems. Mathematical operators can be used to evaluate the values in variables and produce a result. We'll start out with the four basic math operators for now:

- Addition ( + ): used to add two numeric values together.

- Subtraction ( - ): used to subtract a numeric value from another numeric value.

- Multiplication ( * ): used to multiply two numeric values together. (asterisk, Shift-8 on keyboard)

- Division ( / ): used to divide one numeric value into another numeric value.

Some simple example code will help explain operators further. Start a new program in your IDE and type in the following code. When finished execute it to see it in action.

Number1% = 10
Number2% = 20
PRINT "10 minus 20      ="; Number1% - Number2%
PRINT "10 plus 20       ="; Number1% + Number2%
PRINT "10 times 20      ="; Number1% * Number2%
PRINT "10 divided by 20 ="; Number1% / Number2%

Before we get into how the program operates there is something that needs to be addressed first. Have you noticed that there is a semicolon ( ; ) in each line that contains a PRINT statement? You may have noticed that the math game contained them as well. The use of a semicolon in a PRINT statement signifies not to move the cursor down to the next line, but instead leave the cursor where it is and for anything that follows the semicolon to be printed on the same line. You may be wondering why we just didn't use the + operator like we did before:

PRINT "10 minus 20      =" + Number1% - Number2%

Remember that word concatenation you learned earlier? Concatenation in programming terms means to add two string values together. While "10 minus 20" is a literal string, Number1% is not a string but instead an integer type variable. Concatenation will not work here because you can't join a string and an integer together. Try changing the line in your code to match the one above and you'll see that the IDE produces an error. By using the semicolon we can have two dissimilar types of information printed on the same line with one PRINT statement.

In the program example above we can use mathematical operators to instruct QB64 to perform math on the values contained within the integer variables Number1% and Number2%. The result of that calculation will be printed to the screen instead of the values contained in each variable. A better way to do this would be to have the calculation stored in another variable for later use, like so:

Answer% = Number1% - Number2%

Here QB64 does the calculation on Number1% and Number2% and stores the result into Answer%. Modify your code to look like the code below to add this idea:

( This code can be found at .\tutorial\Lesson2\Math.bas )

Number1% = 10
Number2% = 20
Answer1% = Number1% - Number2%
Answer2% = Number1% + Number2%
Answer3% = Number1% * Number2%
Answer4% = Number1% / Number2%
PRINT "10 minus 20      ="; Answer1%
PRINT "10 plus 20       ="; Answer2%
PRINT "10 times 20      ="; Answer3%
PRINT "10 divided by 20 ="; Answer4%

In this example we've created four new variables, Answer1% through Answer4%. We then perform our four math equations and store the results into each respective variable. The PRINT command is then used to show the results on the screen. By pre-computing our values and placing them into variables we can use the results later on if we need them. However, did you notice something terribly wrong with our program's output screen?

Figure 2: Well that's not right?

Can you guess why the variable Answer4% contains the wrong value? Is it a bug in the Pentium processor? Perhaps your math teachers have been wrong all along, how can a computer be wrong, right? The answer lies in the type of variable that Answer4% is. Since we declared the variable Answer4% as an integer type by assigning a percent sign, it can only hold whole numbers. 0.5 is not a whole number so Answer4% will only hold the whole number portion which is zero. As a programmer you will need to keep variable types in mind at all times to avoid making these kinds of mistakes. They can literally drive you nuts!

Let's go ahead and fix our code so the correct value is computed. Change line six to read:

Answer4! = Number1% / Number2%

and then change line ten to read:

PRINT "10 divided by 20 ="; Answer4!

The variable Answer4 can now hold real numbers because it has been declared as a single precision type by using the exclamation point ( ! ). Execute the code again to see if the correct result is now displayed.

Figure 3: Problem solved

A Practical Program

It's time to put everything we have learned so far into one program that has a practical use. Here in the United States we still use the Fahrenheit scale for temperature while most of the world uses the Celsius scale. Converting from Fahrenheit to Celsius is not a difficult task if you know the formula and have a calculator handy, but how many people do you know that can do the conversion in their head? This is a perfect example of where a simple conversion program can come in handy. Type in the following code and execute it to see it in action.

PRINT "Fahrenheit to Celsius Converter"
PRINT "-------------------------------"
PRINT
INPUT "Enter temperature in Fahrenheit: ", Fahrenheit!
Celsius! = 5 * (Fahrenheit! - 32) / 9
PRINT
PRINT
Fahrenheit!; "degrees F ="; Celsius!; "degrees C"

One of the greatest features of QB64 is that very little code can do so much. With just seven lines of code we have written a practical program that solves a problem. The first three lines of code are simple PRINT statements setting up the look of the program. In the fourth line however we are using the INPUT command in a new way. The INPUT command can optionally display a string of text before waiting for keyboard input. So instead of using a PRINT statement on one line to ask the question and then the INPUT statement on another line to wait for keyboard input, as in previous examples, we can combine both functions into one statement. The use of a comma after the literal string question allows you to put the name of the variable that will hold the data entered, in this case Fahrenheit!. Line five contains the conversion formula for converting Fahrenheit to Celsius and stores the result in the variable named Celsius!. The formula on line five follows the order of operations you learned in elementary math class, that is, do the calculations contained in parenthesis first, followed by multiplication and division and then addition and subtraction. For instance, if the user entered the value of 72, the order of operations would be as follows:

Parenthesis first: (72 - 32) for a result of 40

Multiplication next: 5 * 40 for a result of 200

And finally division: 200 / 9 for a result of 22.222 repeating

The final answer of 22.222 repeating would then be stored into the variable Celsius! for later use. Finally, in the last line of the code the variables and literal strings are brought together with a PRINT statement to give the user the answer desired.

Figure 4: The conversion was successful

Variables "Out of the Blue"

In all of the example programs we have done the variables were just created as needed. BASIC was designed to allow this kind of functionality because BASIC was created to be easy to learn for the beginner and simple to use for the person needing some programming skill in their profession. However, in the programming world this is considered bad coding form and most other languages require that they be told about variables beforehand, or declare, the variables that will be used throughout the program. In this course you will be required to declare all of the variables your program will use. Not declaring your variables would only create a bad habit that would be hard to break when you program in another language.

Let's modify our Fahrenheit to Celsius converter and this time declare the variables we are going to use. Make the following changes to your code.

( This code can be found at .\tutorial\Lesson2\FtoCelsius.bas )

'--------------------------------
'- Variable Declaration Section -
'--------------------------------

DIM Fahrenheit! '   holds the user's input temperature in Fahrenheit
DIM Celsius! '      contains the formula's computation into Celsius

'----------------------------
'- Main program begins here -
'----------------------------

PRINT "Fahrenheit to Celsius Converter"
PRINT "-------------------------------"
PRINT
INPUT "Enter temperature in Fahrenheit: ", Fahrenheit!
Celsius! = 5 * (Fahrenheit! - 32) / 9
PRINT
PRINT
Fahrenheit!; "degrees F ="; Celsius!; "degrees C"

The DIM Statement

The DIM statements in the program above are used to declare the variables to the program before use. Using DIM to declare variables pre-allocates sections of RAM for the variables. The benefits of using DIM to declare your variables include:

- It forces the programmer to think about the code before actually coding. Good coding comes from a thorough thought process of the code design, code flow, and variables needed before the fingers ever hit the keyboard.

- It creates a useful table of variables used throughout the program for the programmer to reference later on.

- It creates a QB64 programmer with good coding habits for other languages that require variable declaration.

Save the program again with the changes that were made.

No Comment - The REM Statement

While "no comment" may be a necessity for politicians or movie stars in sticky situations this credo is very bad for coders. In the code example above you see that there are comments added to the code through the use of the REM statement, which can be abbreviated through the use of an apostrophe ( ' ).  This code:

'--------------------------------
'- Variable Declaration Section -
'--------------------------------

and this code:

REM --------------------------------
REM - Variable Declaration Section -
REM --------------------------------

actually mean the same thing to the QB64 IDE, but the abbreviated version ( ' ) looks cleaner and nearly all QB64 coders use the abbreviated form. The REM statement is used to "remark", or comment, the source code. The QB64 IDE and compiler ignore REM statements so they are an excellent way to document sections of code as well as a great way to separate different areas of the code for readability and to comment a single line of code as these two lines did:

DIM Fahrenheit! '   holds the user's input temperature in Fahrenheit
DIM Celsius! '      contains the formula's computation into Celsius

Now, not only do you have a declared listing of variables used throughout the program, you also have a comment after each explaining their use as well! The QB64 compiler simply ignores anything after the REM statement, or ( ' ), on a line. Remarks are for the programmer and are an absolute necessity, especially when code gets to be hundreds, thousands, or even millions of lines long (Windows has millions of lines of C code). In this course you will be required to use comments in your code to explain your code's design and flow. All programmers develop their own style of programming and therefore it is essential that a programmer reading someone else's source code has the original coder's remarks to refer to. Just the code itself would be very confusing to follow. Commenting code takes time and discipline. Don't make the mistake of not getting into the habit of commenting.

Constants - The CONST Statement

There is a special type of variable known as a constant that never changes its value once set. Constants are useful for numbers that have a fixed value, such as PI. Type in the following example and execute it to see how constants can be useful.

( This code can be found at .\tutorial\Lesson2\Circumference.bas )

'--------------------------------
'- Variable declaration section -
'--------------------------------

CONST Pi = 3.1415926 '  the value for Pi

DIM Radius! '           the radius of the circle supplied by the user

'----------------------------
'- Main program begins here -
'----------------------------

PRINT "Circle circumference calculator (2 times Pi times r)"
PRINT "----------------------------------------------------"
PRINT
INPUT "Enter the circle's radius > ", Radius!
PRINT
PRINT
"The circumference of the circle is"; 2 * Pi * Radius!

The CONST key word is used to declare a variable as a constant. Once a constant is set it can't be changed anywhere in the program. Attempting to change the value in a constant will cause the QB64 IDE to generate an error. Many programmers create constant variables in all UPPER CASE to distinguish them from regular variables throughout the source code.

The OPTION _EXPLICIT Statement

By adding the statement OPTION _EXPLICIT as the first line of your code you are informing the IDE that all variables MUST be declared before use. What this means is that you will never be allowed to create variables "out of the blue". Start a new program in your IDE and type in the following line of code:

x = 10

Even though the variable x is created "out of the blue" the IDE will accept the line of code with no issue. Now, insert OPTION _EXPLICIT above your line of code:

OPTION _EXPLICIT
x = 10

As you can see the IDE is now complaining at the bottom of the screen that there is an error in line 2:

Variable 'x' (SINGLE) not defined on line 2
Caused by (or after): X = 10

OPTION _EXPLICIT forces the programmer to declare every variable that is used within the code. Go ahead and declare the variable with a DIM statement to remove the error:

OPTION _EXPLICIT
DIM x%
x% = 10

Notice that x was declared as an integer (%). When x was created "out of the blue" it defaulted to a single type. Single type variables are much slower to work with than integers. By being forced to declare your variables you can be assured they are of the correct type you need for the situation because you had to give some thought to their creation.

OPTION _EXPLICIT also has the added benefit of acting like a spell checker for your variables. Let's say you have a program that is 5000 lines long.  At the top of your code you declared:

DIM Cheetos%

Now, it's 2AM and your typing in line 3485 of your code:

Cheetos% = (Cheteos% + 1) MOD 2

Without OPTION _EXPLICIT at the top of your code the line of code above will happily be accepted by the IDE. The IDE will see Cheteos% as a variable it needs to create "out of the blue".  You type in the remaining code and execute a test run. Hmm, it's not working. You look over your code again and again and you see nothing wrong! Remember, it's 2 in the morning and your tired eyes are skipping right over the misspelling. Now you're tired AND frustrated. If OPTION _EXPLICIT would have been the first line of your code the misspelled Cheteos% variable name would have been caught right away as an undefined variable and the frustration avoided.  I never program without OPTION _EXPLICIT as my first line of code. Since OPTION _EXPLICIT is an IDE directive you can remove it from the code when you are finished or wish to share or post the code for others to view.

Your Turn

Create a program that outputs the screen as shown in Figure 5 below:

Figure 5: Inches to millimeters

Your program must display the number of millimeters contained in the number of inches provided by the user. The program must also:

- Have all variables declared at the beginning of the code.

- Each declared variable must have a comment after it describing its purpose.

- At least one constant must be used in the source code.

When finished save your program as Itomillimeters.BAS.

Click here to see the solution.

Commands and Concepts Learned