Task 4: Introducing Variables  

Contents

Variable Types
Variable Naming
Example Code
Math 101
A Practical Program
Variables "Out of the Blue"
No Comment
Constant Variables
Your Turn - Itomillimeters.BAS
Command Reference


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.




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 Task 3. 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 user 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 statements, otherwise known as a reserved words. 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 task. 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.



As you can see in lines 3 and 4 of the code we used the valued 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.




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.

Go ahead and save this little math game as MathGame.BAS for now. We'll use it again in a later task.



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.




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:




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

Save this code as Math.BAS before proceeding to the next section.


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.



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 operation you learned in elementary math class, that is, do the calculations contained in parenthesis first, followed my 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. Save this example program as FtoCelsius.BAS before continuing on to the next section.



Figure 4 - The Converter in Action


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.




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.

Resave the program with the changes that were made.



No Comment


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 in 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.


Constant Variables


There is a special type of variable known as a constant that never changes it's 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.



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. Go ahead and save this example as Circumference.BAS before continuing.

The carat ( ^ ) symbol is used to denote the value following it as an exponent, or "to the power of". So the math formula:

Pi * Radius! ^ 2

reads as "the value contained in Pi times the radius to the power of 2".

Are you wondering about that CHR$(253) seen in the code? That statement is instructing PRINT to grab character 253 from the ASCII table (the superscript 2) and print it to the screen. Since there is no way for a programmer to enter that character using the keyboard, CHR$() must do it for us. More on that command at a later time.



Your Turn


Create a program that outputs the screen as seen 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.


COMMAND REFERENCE


New commands introduced in this task:

INPUT
DIM
REM or '
CONST

New concepts introduced in this task:

variables
type declarations
literal strings
concatenation
integers
long integers
single precision
double precision
strings
null strings
reserved words
operators ( +, -, *, / )
declare
constant


Commands learned in Task 3:

PRINT

Concepts learned in Task 3:

execute
statement
expression
literal string
syntax error