Ch1 - Output   .   Ch2 - Sequence    .   Ch3 - Variables    .    Ch4 - Input

Ch5 - If decisions    .    Ch6 - While loops   .    Ch7 - Functions

JT Home Page


Chapter 3

Variables And Expressions

Introduction

Conceptually, a variable is like a box with a unique name, into which we can place a value. We may then refer to the box by its name.

Here is a picture of two variables - one is called age, the other salary:

The concept is the the variables (the storage boxes) hold an item of data (e.g. a number) for use further down the program. The jargon is that we assign a value to a variable.

As you will see later, we do this with =, as in:

salary = 33000;
Furthermore, we can do calculations with the values, and can change the value in a variable.

Here, we will look at the rules for introducing variables into a program, but the hard part is deciding which variables are required - it depends on practice, experience, and a knowledge of similar examples.

There are two broad categories of variables in JT - numeric, and string

Numeric Variables

There are two main classes of numeric variable:
- integer (int )
- double

Choose int for exact, whole-number quantities, e.g:

- the number of students in a class.
- the number of locations in a computer's RAM memory.
- the number of lines on a VDU screen.

Choose double for 'decimal-point' quantities, e.g:

- your height in metres.
- average of several integer numbers.
- mass of an atom.

There is a limit on the size of numbers that can be stored, but this limit is large in JT.

string variables

For non-numeric work, e.g. textual data such as someone's name, we can use the string type.

Meaningful Names

As in all programming languages, there are certain rules about how we are allowed to express variable names. In JT, the rules are:

- they can contain only letters or digits.
- they must start with a letter.
- there is no restriction on their length (we would not normally go beyond say 20 though).

Here are some illegal names:

      3times, tax-rate, tax code

Note that upper-case (capitals) are treated as distinct from lower-case, thus:

   PAY
   pay
   Pay

are 3 different variables.

Most programmers stick to lower-case for names.

Sometimes, you will need to use several words for a name. Because we can't use spaces, one convention is to capitalise the start on each word - but not the first word. For example:

   examMark

rather than

   exammark

Use meaningful names! Your program may be read by other programmers, who need to understand its logic as quickly as possible. Meaningful names will help - e.g:

    examMark

is better than

   em, m, emk.

Declaring Variables

Along with most languages, JT insists that you 'introduce'(declare) the name of a variable before you use it. These declarations are grouped together near the top of the program. Here is an example:

Copy and paste it, then run it. Note the display at the top right of the screen, where your variable names are shown, along with their values.

Note that the displayed names are prefixed with 'main.' We will explain this in the chapter on functions. For now, all our programs are contained within:

function void main()
{
and

}

which is a section of program named 'main'.

here are some points on the above

we can put several on a line, separated by a comma. We can use spaces round = , to improve readability if we wish.

Here are some more declarations:

Problems

Create a similar program to the above, containing variable declarations as requested below.

For numeric ones, ensure you choose between int or double.

Invent suitable initial values. (Remember that double values need a decimal point)
Declare these variables:

  1. a variable to contain someone's name
  2. the number of sisters someone has
  3. the number of students in a class
  4. someone's height in metres
  5. the length of a piece of string
  6. my salary in cents

Run the program and check that the correct values are shown in the top right area. Watch out for comma, quote, and semicolon mistakes. Correct any of your errors.

Displaying variables

Use print, printLine, alert, specifying the variable name, as in:

Copy, paste, and run the program. Note the results. They show that the value of the variable is remembered between declaring it and displaying it.

Problems

Amend the above program so that it displays all of the declared variables. It does not matter whether you use alert or print in this example.

Comments    //

Just as you might annotate some notes by jotting down extra stuff on them, so you might wish to clarify a program. Any text after // is ignored, as in:
//some examples of declarations
int age=23;  // declare a variable to hold an age

The above comments are not really useful - they don't add any extra clarification. You will see more useful examples later

4.5 The Assignment Statement

Here are some examples of the simplest form of assignment:

'=' should be read as 'becomes', NOT 'equals'.

In JT, the right-hand-side of the = is evaluated first, resulting in a single number. This is then assigned to (stored in) the variable on the left-hand-side.

For instance, we are allowed to put -

	c = a+b+1;  // c becomes  8 
	c = c+1;    // c becomes  9 

This latter form is particularly common in programming:

c was 8. It is now updated to 9.

the general form of an assignment statement is:

variable = expression;

Note the semicolon - we are using statements, and a semicolon terminates every complete statement.

We can also use strings in assignment.

No apologies for repeating: '=' should be read as 'becomes', NOT 'equals'.

Arithmetic Operators

The above examples assumed you would guess what '+' meant, and it does indeed represent addition. It is an example of an arithmetic operator, and the complete set is:


	+	addition
	-	subtraction
	*	multiplication
	/	division
	%	remainder of integer division

Consider the expression:
6+4*2
Does it result in 20 or 14 ?

In fact, JT follows the algebra convention in performing multiply before add, so the result is 14. The priority of calculation is

innermost brackets ( )    first

    *     /     %                 next

    +     -                         last.

If all the operators have the same priority, left to right order is used. Most programming tasks don't involve a rote conversion of algebraic formulae into JT assignments, but let's have a look at tricky areas:

algebrajt
a y=mx+c y=m*x+c;
b x=(a-b)(a+b) x=(a-b)*(a+b);
c y=3[(a-b)(a+b)]-x y=3*((a-b)*(a+b))-x;
d y=1-2a
        3b
y=1-(2*a)/(3*b);
e a=-b a= -b;

In (a) and (b) the * is not assumed, as it is in maths.

In (c), we are forced to use () in every case.

In (d), if we had written 2*a / 3*b , this would have divided by 3 then multiplied by b.

In (e), we have used - for negation.

To complete our look at the arithmetic operators, let us look at integer division, and the '%' remainder (or modulo ) operator.

We can find what the integer remainder is by:


	a = 3 % 2;		// a becomes  1
	a = 3 % 3;		// a becomes  0

Think this is no use ? Try converting a whole number of cents into the number of dollars and the number of cents left over:

	dollars = cents / 100;
	centsLeft = cents % 100;

Type Conversion in Assignment

JT lets us store an int into a double, but not a double in an int.

int i=9;
double d=8.7;
d=i;   // ok
i = d; //  no

Increment/decrement.

Instead of
 
n = n+1;
or
 b = b-1;
we may put
 n++;
or     
 b--;

Problems

What are the final values of a,b,c after the following assignment statements?


int a = 1, b = 2, c = 3;
a = b+c;
a = a+1;
b = a;
b = a+b*10;
c = b % 10;

(do it on paper first, then run it to check your answers.)


Ch1 - Output   .   Ch2 - Sequence    .   Ch3 - Variables    .    Ch4 - Input

Ch5 - If decisions    .    Ch6 - While loops   .    Ch7 - Functions

JT Home Page