previous page main index next page
 

Text Variables

All the programs you've done so far have used numeric variables - ie numbers. Each variable is of a particular type - real or integer - and each has its own name. Variables can be used in calculations as, for example:

          average := total / 3;

In this case, average is calculated as having the value of total divided by 3. There are, however, other types of variables...

Variables used to represent text are often called string variables. An example would be variable containing your name.

Example 8

  • type in the following program then compile and run it
     
PROGRAM text;            {using text variables}
VAR                      {by A Programmer}
  name : STRING[10];
  age  : INTEGER;
BEGIN
  name := 'A Programmer';        {use your name here}
  age := 15;
  WRITELN('my name is ', name);
  WRITELN('my age is ', age)
END.
 
The variable called name is defined as a string variable in line 3:

  name : STRING[10];

The number 10 in the square brackets means that the string can have up to 10 letters, or characters, in it. This program, of course, doesn't do a great deal. Apart from anything else, it prints the same thing every time you run it.

  • edit the program to look like this:
     
PROGRAM text;            {using text variables}
VAR                      {by A Programmer}
  name : STRING[10];
  age : INTEGER;
  days : INTEGER;
BEGIN
  WRITE('enter your name : ');
  READLN(name);
  WRITE('enter your age : ');
  READLN(age);
  days := 365 * age;
  WRITELN('hello ', name);
  WRITELN('you are ', age);
  WRITELN('you must be at least ', days, ' days old!')
END.
  • save the program as age.pas

At least this program produces different output depending on what you type in. You'll notice that a couple of the instructions used WRITE instead of WRITELN. Can you remember what difference it makes?

  • edit your program to use WRITELN instead of WRITE
  • write a short description of the difference in your work book
  • explain which of the two you think worked better
  • explain what happens if you type in a name with more than 10 letters
     
previous page main index next page
 
© 2001