Tải bản đầy đủ (.pdf) (18 trang)

The pascal programming language

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (880.11 KB, 18 trang )

Computer Studies Programming using Turbo Pascal
Notes - 1 -

The Pascal programming language was developed, around the 1970s, by Nicholas Wirth. It was
developed as a first language for programming students and serves the purpose well. Pascal is
one of the easiest languages to learn, and it encourages beginners to develop good programming
skills.
Easy to learn
It is easy to learn because the language has a relatively small set of words, and these are close
enough to ordinary English to be easy to understand and remember. Even before you start to
learn the language, you should be able to read a Pascal program’s code and be able to make some
sense of it.
Example

program first;

begin
write(‘Hello World’);
end.

The basic structure
At the simplest, a program takes this shape:
program title;

begin
statement;
statement;
statement;
end.

The important things to notice here are:


Programs always start with the word program followed by the name. The name must be
a single word – no spaces or punctuation – but can normally be of any length.
The start of the active part of the program is marked by begin.
The end of the active part is marked by end.
program, begin and end are all reserved words, ones with a special meaning. They can
be written in lower case or capitals.
The full stop at the end is essential.
A program can contain any number of statements.
It starts here…
This is the code of a Pascal
program, and it is called
first
.

write
must put the text on the
screen.

… and it ends here
Computer Studies Programming using Turbo Pascal
Notes - 2 -
A statement will usually be on a line by itself, but can be spread over several.
Each statement is separated from the next by a semi-colon. This is normally written at
the end of the line.
To make th eprogram easier to read, lines may be indented. This is more useful in more
complex programs, where different levels of indents can help to bring out the structure.
Whether and how far you indent is entirely up to you.
Let’s get it started…
When using Turbo Pascal, you will working with two different types of screens,
 The text-editor: this is a blue screen

where you will be typing your
programs.
 The output screen: this is where you
will see the results when you compile
(run) your program – in other words, where a program works.
Writing a simple program – the use of write and writeln statements
Try this program to see how text, integers and decimal values are displayed on the screen.
program writing;
uses crt;

begin
clrscr;
writeln(‘This is a text item.’,‘Here is another’);
writeln(‘One more ’,‘and the last’);
writeln(1,2,3,4,5); {integers or whole numbers}
writeln(12345.678, 0.123); {number with decimal fraction}
readln;
end.
To see the program work, click on RUN in the menu bar and click on
RUN in the menu.
 Write down the results you see on the screen in the box below.








Instead of writeln, type the command write. What happens to the output? Write

down the results you see on the screen in the box below.
Comments written inside {curly brackets}
are ignored by the compiler – i.e. when
the program is run.
Computer Studies Programming using Turbo Pascal
Notes - 3 -







So what’s the difference between write and writeln?
 write  ______________________________________________________________
_______________________________________________________________________
 writeln  ____________________________________________________________
_______________________________________________________________________

The clrscr command
This command is used to clear the output screen from any characters and put the
cursor in the top-left corner of the screen.

Why not add a few colours? – the use of textcolor and textbackground
The output screen can be very dull. It usually displays grey text and a black
background. Type the following program and see and then write down what you
think textcolor and textbackground are used for.

program colourful;
uses crt;


begin
clrscr;
textbackground(14);
textcolor(13);
writeln(‘Testing colours’);
readln;
textcolor(12);
writeln(‘Still testing colours’);
readln;
end.
So what do the command textcolor and textbackground do?
 textcolor  _________________________________________________________
_______________________________________________________________________
 textbackground  ___________________________________________________
_______________________________________________________________________
Computer Studies Programming using Turbo Pascal
Notes - 4 -
But why doesn’t my program work?
Have you every asked this question yet? If you do not use the correct syntax
(i.e. grammar) when typing a Pascal program, it simply won’t work. Your
program must be error-free in order to work.
When the compiler meets an error in a program, the cursor stops in the line
after the error. An error message is displayed at the top of the screen. If you press F1 the error
message is further explained for you.
The error message The help window

The following program has errors. Correct the errors and make the program work on a
computer.


program colourful text;
uses crt;

begin
clrcsr;
textcolour(green);
writeln(‘I am programming);
textcolor(12)
writeln(Using Turbo Pascal’);
readln;
end
 In the box below write down the corrected version of the above program.

_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Computer Studies Programming using Turbo Pascal
Notes - 5 -
The four basic arithmetic operations
The four basic arithmetic operations that one can use in Pascal are :
plus


+
minus

-
multiply

*
divide

DIV, MOD, /
You will now be looking at a few exercises to see how each operation can work.
Addition, Subtraction and Multiplication
Adding, subtracting and multiplying numbers in Pascal couldn’t be easier. Copy and run the
following program on a computer to see how these arithmetic operations work.
program arithmetic_operations;
{adding, subtracting and multiplying}
uses crt;

begin
clrscr;
textcolor(green);
writeln(‘Addition: 5 + 2 = ‘,5 + 2);
writeln(‘Subtraction: 15 - 7 = ‘,15 - 7);
writeln(‘Multiplication: 8 x 3 = ‘,8 * 3);
readln;
end.
 Write down the results that you see on the screen in the box below.






Division
Using Pascal, there are three ways in which you can divide two numbers. Try out each method.
Division using ‘/’
program division;
{division using /}
uses crt;

begin
clrscr;
writeln(‘Division: 17 / 3 = ‘,17/3);
readln;
end.
 Write down the output that you see on the screen in the box below.



Computer Studies Programming using Turbo Pascal
Notes - 6 -
Counting the decimal places
Look at the result from the previous program. Can you see too many zeros? How about we
format the number to two decimal places instead?
Go back to the previous program. Change the line to the one that is displayed here.
writeln(‘Division: 17 / 3 = ‘,17/3:0:2);

 Now write down the output that you see on the screen in the box below.




Division using ‘DIV’ and ‘MOD’
DIV and MOD are two other ways of performing division. But with a difference. Copy and run
the following program on a computer. Look at the results – what do you think is the difference
between DIV and MOD?
program division;
{division using DIV and MOD}
uses crt;

begin
clrscr;
writeln(‘Division: 17 DIV 3 = ‘,17 DIV 3);
writeln(‘Division: 17 MOD 3 = ‘,17 MOD 3);
readln;
end.
 Write down the output that you see on the screen in the box below.



So what’s the difference between DIV and MOD?
 DIV  ________________________________________________
_______________________________________________________________________
 MOD  ________________________________________________________________
_______________________________________________________________________
So what have you been doin’…?
Up till now you have been writing out and running simple programs on a computer
using Pascal. Very straight-forward programs. They perform simple
tasks that are set by YOU, the programmer. But how about a little
This
means that the

number will be displayed
to 2 decimal places.

Computer Studies Programming using Turbo Pascal
Notes - 7 -
input from the user while the program is running?
The next part of these notes will show you how to accept inputs while a program is running.
Variables and data types
If you want to handle any data while the program is running, you must set up variables. These
are areas of memory, idenified by a name written into the program. When setting up a variable,
you must say what type of data is to be stored there, as different types require different amounts
of memory.
Declaring a variable
To accept input while a program is running, you have to declare a variable name and its datatype.
A variable name:
must be a single word;
can contain letters and numbers;
cannot start with a number.
You cannot use a reserved word (words used by Pascal) as a variable name, e.g. begin.
A datatype is used to specify the type of input. The following are the datatypes you will be
using:
integer A whole number, in the range -32,768 to
+32,767
real Any number, with or without a decimal
fraction
char A single character, which can be a letter,
symbol or digit – in fact, any character from
the ASCII set.
boolean These can only store the values ‘TRUE’ or
‘FALSE’. Boolean variables are generally

used to store the results of logical tests.
string Can be used to store a set of zero or more
characters.
INTEGER and REAL data types
You’ve typed programs that add numbers – the only problem is that they only add the same two
numbers! The following is a program that adds two numbers that the user can enter while the
program is running. Copy and run the following program.

Computer Studies Programming using Turbo Pascal
Notes - 8 -
program input_numbers;
{adding numbers using variables}
uses crt;

{this is the part where you declare a variable}
var
num1, num2: integer; {an integer is a whole number}

begin
clrscr;
writeln(‘Enter the FIRST number: ‘);
readln(num1);
writeln(‘Enter the SECOND number: ‘);
readln(num2);
writeln(‘Result after adding the numbers is ‘,num1 + num2);
readln;
end.
 Write down the output that you see on the screen in the box below.







You have just written a program that adds any two numbers. Well done!
Modify the program above so that it will output the subtraction, multiplication and
division for the two numbers entered by the user.
 In the box below write down the new version of the above program.

_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________

Declaring variables.
Notice the use of var
when declaring variables.
Computer Studies Programming using Turbo Pascal
Notes - 9 -

The assignment statement
There are two ways of storing variables: they can come in from the keyboard (the user’s input),
or values can be assigned from within the program. You have seen how to input numbers and
store them in variables when you typed and compiled the previous program (on page 8).
Variable := value
Values are assigned to variables with the operator “ := ” – a colon followed by an equals sign.
The variable name sits to the left, and on the right is an actual value, another variable, a function,
or an expression that produces a value. Here are some examples:
number_1 := 99;
number_2 := 103;
answer := number_1 + number_2;
total := total + next;
name := ‘SAM’;
Copy and run the following program.
program values_variables;
{assigning values to variables}
uses crt;

var
a, b, c :integer;
decimal :real;
letter :char;
YesNo :boolean;

begin
clrscr;
a := 2;
b := 3;
c := a + b;
decimal := 9.99;

letter := ‘X’;
YesNo := TRUE;

writeln(‘a = ‘,a ,’b = ‘,b ,’c = ‘,c);
writeln(‘Decimal holds ‘,decimal:0:2);
writeln(‘The letter is ‘,letter);
writeln(‘The value of YesNo is ‘,YesNo);

readln;
end.

 Write down the output that you see on the screen in the box below.








Computer Studies Programming using Turbo Pascal
Notes - 10 -
Exercises
Read the following problems and then try to solve them by writing a program. Once the
programs work successfully on a computer, write them out on a foolscape and pass them on to
your teacher.

1. Write a program where the user will be asked to input his/her name and the year of birth.
The program will calculate how old the person is and then output the person’s name
together with his/her age.

 Write down the output that you see on the screen in the box below.








2. Write a Fahrenheit to Centrigrade conversion program. The progra will take a Fahrenheit
temperature as input and ouputs the corresponding temperature in Centigrade. Use the
formula C = ( F – 32 ) x
5
/
9
where C is the temperature in Centirgrade and F is the
temperature in Fahrenheit.
 Write down the output that you see on the screen in the box below.








3. Write a program that accepts three numbers as input, calculates their total and average,
and outputs the results on screen.
 Write down the output that you see on the screen in the box below.








Computer Studies Programming using Turbo Pascal
Notes - 11 -
Conditional statements
The programs you have seen up till now are sequential – i.e. the program goes through all the
instructions, one after another. It is often necessary to take different routes through a program
depending on some condition. This is known as branching. Branches make a program flexible,
allowing a program to vary its actions in response to incoming data. This can be achieved in
Pascal by the if-then statement.
if-then statement
This is the basic syntax:
if test then statement;
… or where there are several statements:
if test
then
begin
statements;
end;
The test checks the value held by a variable. if the condition proves true, then the program
performs the following statement(s). If the condition does not prove true, the statements are
ignored.
Conditional expressions
The tests use these operators:
=
is equal to

<>
is not equal to
<=
is less than or equal to
>=
is greater than or equal to
Some examples of valid tests:
if x > 99 true if the value in x is greater than 99
if letter <= ‘Z’
true if a capital letter or other character lower
down in the ASCII set
if ans <> correct true if th evariables do not match
Copy and run the following program.
program calculator;
uses crt;

var
num1, num2, answer :real;
op :char;

Computer Studies Programming using Turbo Pascal
Notes - 12 -
begin
clrscr;
write(‘Enter first number: ‘);
readln(num1);
write(‘Enter second number: ‘);
readln(num2);
write(‘What sort of calculation (+ - * /) : ‘);
readln(op);


if op = ‘+’ then answer := num1 + num2:
if op = ‘-’ then answer := num1 - num2:
if op = ‘*’ then answer := num1 * num2:
if op = ‘/’ then answer := num1 / num2:

write(‘Then answer is ‘, answer:0:3);
readln;
end.

 Write down the output that you see on the screen in the box below.








Write a program where the user has to input an exam score between 0 and 100. If the
score is greater than or equal to 50, the word PASS is displayed. If it is less, the phrase
TRY AGAIN is displayed.
 Write down the program in the space provided below.

_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________

_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________


P.S. instead of using two if-then statements, you can use one if-then-else statement. This is an
extended form of if… which handles these situations neatly:
if test
then statements-if-true
else statements-if-false;

Computer Studies Programming using Turbo Pascal
Notes - 13 -
For Loop
‘Program flow’ refers to the order in which a program’s instructions are carried out. So far, all
the example programs have run straight through a sequence and then stopped. There are few
practical uses for such simple programs. The addition of loops and branches makes programs far
more useful and powerful.
The for loop probably offers the simplest way to repeat a set of instructions. The basic shape is
this:
for variable := start_value to end_value do
statement or block of statements;
When the program reaches this point for the first time, the variable is given the start_value. The
following statement is executed and the flow loops back to the for line. The variable is
incremented by 1, and the statement executed again. The flow continues to go round the loop
until the variable reaches the end_value.
Copy and run the following program.
Program fortimes;

Var

loop: integer;
table: integer;

begin
write(‘Which times table would you like ? ’);
readln(table);
for loop:= 1 to 12 do
writeln(loop:4,’times ‘,table:2,’=’,loop*table:4);
readln;
end.

 Write down the output that you see on the screen in the box below.








Try different start and end values and note their effects. What happens if the end value is less
than the start value?

Type a program where the user will enter a string variable. This will then be displayed
ten times on the screen.
The loop variable is normally an integer


it can be called anything, but the name
‘loop’ makes its purpose very clear.

Computer Studies Programming using Turbo Pascal
Notes - 14 -
Copy and run the following program.
Program addloop;

Var
loop: integer;
num: integer;
total: integer;
howmany: integer;

begin
write(‘How many numbers do you want to add?’);
readln(howmany);
total:=0;
for loop:=1 to howmany do
begin
writeln(‘Enter number: ‘);
readln(num);
total:=total + num;
end;
writeln(‘Total = ‘,total);
end.

Make changes to the above program so that it will calculate the average of the numbers
that have been entered.
The two little programs given here are not just more examples of loops. Both display the
printable part of the ASCII set. This – the American Standard Codes for Information Interchange
– translates characters (letters, digits and symbols) into numbers that computers can understand.
Pascal has two functions to switch between characters and their ASCII number codes:

chr(n) turns a number into its character; e.g chr(65) is ‘A’
ord(c) turns a character into an ASCII code; e.g. ord(‘A’) is 65.
Program ascloop;
uses crt;
var
n: integer;
begin
clrscr;
for n := 32 to 128 do
write(n:4, char(n):4);
readln;
end.

Program charloop;
uses crt;
var
c: char;
begin
clrscr;
for c:= ‘ ‘ to ‘-‘ do
write(ord(c):4, c:4);
readln;
end.
Initalise the total at the start
If you use variables for the
start or end values, they must
be the same type as the loop
variable – normally integers
Try putting this inside the loop


Characters from codes
Codes from characters
Computer Studies Programming using Turbo Pascal
Notes - 15 -
Repeat-Until Loop
Here is another way to loop, but in this case, the number of iterations is not fixed. With this
structure, the flow passes through the block then keeps looping back to the start until a value
entered by the user, or calculated by the program, satisfies its exit condition. The basic shape is:
repeat
statement or block of statements;
until exit_test

If there are several statements in the loop, you do not need begin…end to hold them
together. The repeat and until words act as brackets to enclose the block.
The exit_test will usually compare a variable with a value or with another varible.
In the example program, the flow loops around, taking in and adding a number to the total, until
the user enters ‘0’ (zero). Copy and run the following program.
Program repeatadd;
uses crt;
var
num: integer;
total: integer;
begin
clrscr;
total:= 0;
{Initialize the variable total. Setting the value of a variable.}

repeat
writeln(‘Enter number or 0 to end: ‘);
readln(num);

total:= total + num;
writeln(‘Total = ‘,total);
until num = 0;
readln;
end.
 Write down the output that you see on the screen in the box below.








While Loop
While loops are used in much the same way as repeat loops, but there is one major difference
between them – while loops are tested on entry; repeat loops are tested on exit. As a result, the
statements in a repeat loop are always executed at least once, but those in a while loop may not
be executed at all.
Computer Studies Programming using Turbo Pascal
Notes - 16 -
Here is the basic shape of the while loop – compare it with the shape of the repeat loop earlier
on:
While (test) do
statement or block of statements;

You must give an initial value to the variable beign tested, even though it may be
overwritten as soon as the loop statements are executed.
If you want to loop round several statements, they must be enclosed in begin and end.
Copy and run the following program.

Program while_loop; {example 1)
uses crt;
var
num: integer;
total: integer;
begin
clrscr;
total:= 0;

writeln(‘Enter number or 0 to end: ‘);
readln(num);

while num <> 0 do
begin
total:= total + num;
writeln(‘Total = ‘,total);
writeln(‘Enter number or 0 to end: ‘);
readln(num);
end;

readln;
end.

A common use for while loops is to collect input where the user has failed to enter suitable data
on first asking. Here is an example. Copy and run the following program.

Program while_loop; {example 2}
uses crt;
var
answer: integer;

begin
clrscr;
write(‘109 + 8 = ‘);
readln(answer);

while answer <> 117 do
begin
writeln(‘WRONG! Please try again.’);
write(‘109 + 8 = ‘);
readln(answer);
end;

write(‘WELL DONE!’);
readln
end.
Computer Studies Programming using Turbo Pascal
Notes - 17 -
Arrays
Arrays provide an easy means to handle large quantities of data. An array is a collection of
variables – of any type – all with the same name.
Arrays provide an easy way to handle large amounts of data. It is a way of organising data in
memory.
Defining an array
Think of an array as a table, or a list, with numbered rows. Arrays are defined (in the usual var
area) by specifying their size and type like this:
var
mark: array[1 25] of integer;

This statement defines 25 integer variables, which will be referred to as mark[1], mark[2],
mark[3], … mark[25]. The number in brackets is called the index or subscript of the array.

An array may also be used to hold strings of characters. For example you could define an array
to hold the names of the months:
var
month_name: array[1 12] of string[9];

The array could be initialised with 12 statements of the form …
month_name[1]:= ‘January’;
month_name[2]:= ‘February’;
etc …
Contents of arrays are usually processed using a loop.
The following program makes use of arrays to store the names and marks for 5 students. Copy
and run the following program.
Program examinations;
{using arrays)
uses crt;
const
max = 5;
var
name: array[1 max] of string[15];
mark: array[1 max] of integer;
loop, total, pos: integer;
average: real;
begin
clrscr;
total:= 0;

{inputting name and marks}
For loop:= 1 to max do
Begin
Write(‘Input name of student: ‘);

Readln(name[loop]);
Max
is a constant value, i.e. it
doesn’t change. It will be used to
determine the number of students
this program can handle

Name is an array that will store 5
variables (max = 5) of string type.
String[15] means tha each variable
can be 15 characters long.

Computer Studies Programming using Turbo Pascal
Notes - 18 -
Write(‘Input mark: ‘);
Readln(mark[loop]);
End;

{calculating average mark}
For loop:= 1 to max do
total:= total + mark[loop];
average:= total/max;

writeln(‘The average for the class is ‘, average:0:2);

{finding highest mark}
pos:= 1;
For loop:= 2 to max do
If mark[pos] < mark[loop]
Then pos:= loop;

Writeln(name[pos],’ has obtained the highest mark of ‘,mark[pos]);
Readln;
End.
Think …
Look at the program that you have just typed and answer the following questions on a separate
piece of paper (preferably a foolscape):
1. What is the purpose of the constant MAX?
2. Why is the variable AVERAGE declared as a real datatype?
3. Which variable is initalized at the start of the program? What does initalized mean?
4. What would you change in the program so that it will accept 22 students?
5. What is the purpose of the variable POS?
6. Make the necessary changes to the program so that it will also find the lowest mark.

Exercise
Write a program (using the Pascal programming language) that allows a user to enter the names
and marks for eight students. The program should prompt the user to enter a name and a mark,
check that the mark is within the range 0 <= mark <= 100  otherwise the program asks the user
to type the mark again. The program outputs the student’s name and grade. Grades are awarded
according to the following grade boundaries:
80 < mark <= 100 grade A
60 < mark <= 80 grade B
40 < mark <= 60 grade C
mark <= 40 failed
Make the program as user friendly as possible and include inline comments. But before you start
typing your program, design a flowchart first.
HINT: use one-dimensional arrays to store the names, marks and grades of the students.

×