BASIC INPUT AND OUTPUT



As you probably know, nearly all computer programs take input from the user.
If you don't know how to take input then you won't get very far in the programming world.

Pascal has two major functions for taking input from the user. These are:-

read

Syntax:            What does syntax mean?
read (variable);

Explanation:
This reads all the characters typed, until the user presses enter, into the variable.
If the variable is of type integer, and the user types in string characters, then
an error will occur. If the variable is a string of defined length then read will only
take the first X characters from the line and put them into the string, where X is the size
of the string. Read does not move the cursor to the next line after input.

readln

Syntax:
readln (variable);

Explanation:
This is exactly the same as read except for the fact that it moves the cursor to the next line after the user presses enter.




The output commands in pascal are very similar in syntax to the input commands.

write

Syntax:
write (variable);
write (variable:f)
write (real variable:f:d);

f=field width d=number of decimal places

Explanation:
The write command displays a string of characters on the screen. When a field width is included, the writing
is right aligned within the field width e.g. write ('Hello':10); will produce the following output...

00000Hello

(0=space)

Notice that 'Hello' is right-aligned within the field of ten characters , the remaining spaces coming before 'Hello'

When writing real numbers, you must specify the field width and number of decimal places displayed, otherwise pascal will write it to the screen in standard form (this is not good). A field width of zero will just write the real as if you had not specified a field width.

If you want to write a combination of things, separate these by a comma. e.g.
write ('Hello ' , name , ', you weigh ' , weight:0:2 , ' kg.');
The above will write something like this... Hello Joe Bob, you weigh 76.54 kg.

Note: The write command does not move the cursor to the next line after execution.

writeln

Syntax:
writeln (variable);
writeln (variable:f)
writeln (real variable:f:d);

f=field width d=number of decimal places

Explanation:
The writeln command is exactly the same as the write command except for the fact that it moves the cursor
to the next line after execution.



NOTE: All of the above commands are also used when reading and writing to files. This will be covered later.

EXAMPLE PROGRAM

Program example;
{This is an example program for input and output}

uses Crt;
var

begin
end.


Previous lesson(variables)     Main Menu     Next lesson(Maths)