What is a variable?

The best way to describe a variable is as a 'box'. This box has special properties...

1. The box can contain only a single value at any time
2. The box has a name in order to reference it
3. Values can be taken out of the box and new values can be put in.

Variable Names

Before a variable can be used it must be given a name. This name specifies the name of the 'box' to obtain a value from.

The name of a variable can be any combination of letters and numbers as long as it is unique.

Variable Types

There are three types of variable that can be used in a TNT Basic program...

Integers
An integer variable can hold any whole number value. They can hold both positive and negative numbers.

Floats
A floating point variable can hold any number both positive and negative. This includes decimal point numbers.

Strings
A string value can hold any sequence of letters. e.g. "Cat", "Dog" or "Chicken".

A variable can only be one of these three types.

Declaring Variables

Before a variable can be used in a program it must be declared. e.g.

integer x
float y
string z

or...

int x
float y
str z

This piece of code declares x to be a variable of type integer, y to be a floating point number and z to be a string.

Once a variable has been declared it is impossible to use the same name to declare another variable.

Variables can only be used as the type they are initially declared to be.

Variable Values

Take a look at this example....

int chicken
chicken=5
chicken=3
Print chicken

This piece of code will print the number 3. This happens because...

1. The variable chicken is given the value 5
2.
chicken's value is then replaced with 3
3. The value of
chicken is output

This is because each variable can only hold one value at a time. When a new one is put in, the old one is lost.

The Power of Variables

The real power of variables comes from the fact that we can change the values contained in them in any way we want.

int chicken
int dog
chicken=10
dog=5
chicken=chicken/dog

This will eventually finish with dog containing the value 5 and chicken containing the value 2. The last line can be read as chicken equals 10 divided by 5.


Table of contents