As you probably know, nearly all computer programs take input from
the user.
A D V E R T I S E M E N T
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: 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
name : string[30];
begin
clrscr; {This clears the screen}
write ('What is your name? '); {Writes the question without moveing the
cursor to the next line}
readln (name); {take input from user}
writeln ('Hello ', name); {Output Hello joebob}
while not keypressed do; {waits for a key to be
pressed}