Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
116 views

Pascal Programming

Here are the solutions to the exercises in Pascal code: 1. See previous slide for conversions of pseudocode algorithms to Pascal code. 2. Program SquareNumber(input, output); Var num, square: integer; Begin writeln('Enter a number: '); readln(num); square := num * num; writeln('The number is: ', num); writeln('Its square is: ', square); End. 3. Program KgToLbs(input, output); Const kgToLbs = 2.2; Var kg, lbs: real; Begin writeln('Enter weight in kg: ');

Uploaded by

sheanetienne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views

Pascal Programming

Here are the solutions to the exercises in Pascal code: 1. See previous slide for conversions of pseudocode algorithms to Pascal code. 2. Program SquareNumber(input, output); Var num, square: integer; Begin writeln('Enter a number: '); readln(num); square := num * num; writeln('The number is: ', num); writeln('Its square is: ', square); End. 3. Program KgToLbs(input, output); Const kgToLbs = 2.2; Var kg, lbs: real; Begin writeln('Enter weight in kg: ');

Uploaded by

sheanetienne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

PASCAL

PROGRAMMING
INTRODUCTION
PASCAL is a programming language named after the 17th century mathematician
Blaise Pascal.

The Pascal programming language:


⚫ Provides a teaching language that highlights concepts common to all computer
languages.
⚫ It standardizes the language in such a way that it makes programs easy to
write.

Basic format of every Pascal program


Every Pascal program has the same essential format, which is illustrated
below:
Program Title(input , output);
Begin
program statement(s);
End.
KEYWORDS AND IDENTIFIERS
Keywords are reserved words, i.e. You cannot use keywords to describe
variables. Some examples include:

Program Begin End If Else


While Do Repeat Until For
Const Var Procedure Function Then

Identifiers: In the previous example, TITLE is the name the programmer gave to
the Pascal program. It is an identifier. Identifiers begin with a letter, then
followed by any digit, letter or the underscore character ( _ ).

Which of the following are valid Pascal identifiers?


birthday Too_hot? First_Initial
grade 1stprogram down.to.earth
see you OldName Multiplication2
VARIABLES
A variable is an item that allows you to store data into it.
Variable names are a maximum of 32 alphanumeric characters. Older Pascal
compilers recognizes the first 8 characters.

Naming a variable : The 1st letter of the variable must be alphabetic (A to Z) or


(a to z), followed by either letters, a number or an underscore eg. num, age2, avg,
sum, first_num etc.

Variable (Data) Types:


⚫ Integer – to store integer or ‘whole’ numbers, eg.) 45 234 1245 -99
⚫ Real – to store fractional numbers, eg.) 3.45 567.78 -99.99
⚫ Char - to store a single character such as a letter, digit or punctuation
mark, eg.) A, b, 4, x, Y
⚫ String – to store a collection of characters, eg. Apple abc123
⚫ Boolean - used for values that are True/False or Yes/No type responses
INPUT, PROCESS & OUTPUT
The majority of programs will follow the Input - Process - Output cycle.

INPUT
In Pascal we use two commands together in order to receive input from the
user. We first use a writeln or write statement to display a message explaining
the type of input required and then a readln statement to store the data in an
appropriate variable, for example:
writeln('What is your name?');
readln(name);
N.B. the single quote (‘) characters around the question. There is no need to use
single quotes in the readln line. Each line ends with a semi-colon ;

writeln – displays a message and sends the cursor in the output screen to the next
line without pressing ‘Enter’.
write – displays a message but does not sent the cursor to the next line
readln – reads the data to be stored on separate lines
read – reads the data to be stored on the same line. Each piece of data is usually
separated by a space.
INPUT, PROCESS & OUTPUT CONT’D
PROCESS
Processing usually involves changing values of variables or creating extra variables
by combining other variables e.g. adding two numbers together to come up with
third. In Pascal we use the assign := sign to perform calculation. While it looks
very similar to the equals = symbol it is different. Equals (=) is used for
comparisons while assign (:=) is for storing values. All types of variables can have
values placed in them using the assign sign, for example:

age := 2000 - yearborn;


name := 'Fred Fruit';
total := number1 + number2;

N.B. Single quotation marks are only required for storing strings or characters
INPUT, PROCESS & OUTPUT CONT’D
OUTPUT
The final stage is the outputting of processed data or information to the user. Once
again we use the writeln or write statements. The basic rule to follow is that text
that you create in contained within single quotation marks (') and variables are
contained between commas (,) unless they are at the start or end of the output, for
example:
writeln('Thank you for using this program.');
writeln(name,' is in Year 10');
writeln(name,' will turn ',age,' in 2000');

When displaying real type variables it is necessary to format the output by


specifying how many spaces you wish to leave and how many decimal places you
would like to display. As a general rule 4 spaces and 2 decimal places works in
most cases, for example:

writeln('The amount owing is $',amountowed:4:2);


SYNTAX
Syntax is a set of rules for combining the various elements that make up a
programming language.

It the very precise way in which the statements in a program must be written in
order to be understood. The syntax allows the programmer to create a correctly
structured statement that is ‘legal’ although it does not guarantee that the
statement will be useful:

⚫ All program statements and lines are terminated with a semi-colon (;)
⚫ A semi-colon is not required after any of the Pascal keywords
⚫ The program name and variables must be one word, no spaces
⚫ The program name and variable names cannot match
⚫ Variables of each type must be declared separately
⚫ The use of indentation and spacing helps in the presentation and readability of
the coding
⚫ After the last END, a full stop (.) is required
PROGRAM STRUCTURE
Nearly all structured programs share a similar overall structure:
⚫ Statements to establish the start of the program
⚫ Variable declarations
⚫ Program statement(s) – blocks of code

Example 1: Example 2:

Program MYFIRST(output); Program AddNumbers(input,output);


Var
Begin a,b,sum:integer
writeln(‘Hello. How are you?’); Begin
End. a:=2; b:=5;
sum:= a + b;
writeln(‘The sum is: ‘,sum);
End.
COMMENTS
Comments are inserted into Pascal programs by enclosing the comment within
{ } braces. Comments are ignored by the computer, but are helpful to explain how
the program works to other programmers.

program DEMOPROG (output);


begin
write('Hello there.');
{the write statement does not set the cursor to the beginning of the next line.
}
writeln('This is getting boring.')
{ This is printed on the same line as Hello there, but now the cursor moves to
the beginning of the next line, because this time we used writeln instead of
write }
end.
CONVERTING PSEUDOCODE TO
PASCAL CODE
Eg. 1) Write an program which prompts the user to input his/her name and prints a welcome
message to the user.

ALGORITHM PASCAL CODE

Algorithm Welcome Program Welcome;


This algorithm prints a welcome message for {This program prints a welcome message for
the user the user}
Start Begin
Print (‘Welcome to the world of problem- writeln(‘Welcome to the world of
solving !’) problem-
Stop solving!’);
End.
CONVERTING PSEUDOCODE TO PASCAL
CODE CONT’D
Eg. 2) Write a program to prompt the user to input 3 numbers and calculate and
print the total and average

Algorithm FindAverage Program FindAverage(input,output);


This algorithm finds the total and average of {This program finds the total and average
3 numbers which the user inputs. of 3 numbers which the user inputs}

num1,num2,num3 – stores the 3 numbers Var


sum – stores the sum of the 3 numbers num1, num2, num3, Sum: integer;
average – stores the average of the 3 numbers Average: real;
Start Begin
Set num1,num2,num3 to 0 num1:=0; num2:=0; num3:=0;
Print(‘Please enter 3 numbers’) writeln(‘Please enter 3 numbers’);
Input (num1,num2,num3) readln(num1,num2,num3);
sum = num1+num2+num3 sum:= num1+num2+num3;
average = Sum/3 average:= sum/3;
Print(‘The sum is: ‘,sum) writeln(‘The sum is: ‘,sum);
Print(‘The average is: ‘,average) writeln(‘The average is: ‘,average:4:2);
Stop End.
THE ‘CONST’ DECLARATION
⚫ The const declaration is used to define symbolic constants.
⚫ Constants are like variables except that their values can't change.
⚫ A value is assigned to a constant when you create it.
⚫ Const is used instead of Var when declaring a constant.
⚫ Constants are used for values that do not change, such as the value of pi.

Eg.) Write a program which prompts the user to enter the radius of a circle and calculate the area of
the circle. [Area of a circle = πr2]

Program CircleArea(input , output);


Const
pi = 3.1416;
Var
r: integer;
area: real;
Begin
writeln(‘Please enter the radius of the circle’);
readln(r);
area:= pi*r^2;
writeln(‘Area = ‘,area:4:2);
End.
EXERCISE 5
1. Code the algorithms from Exercise 1 in Pascal code.

2. Write a program to request a number and print the number and its
square.

3. Write a program which requests a user to enter a weight in kilograms


and converts it into pounds. [1kg = 2.2 lbs]

4. Write a program to which prompts the user to enter two integer values
L and B, which represents the length and breadth of a rectangle, and
calculates the area of the rectangle.

5. A ball is thrown vertically upwards with an initial speed of U metres


per
second. Its height H after time T is given by:
H = UT – 4.9T2
Write a program which request U and T, and prints the height of the
ball after T seconds.
IF...THEN...ELSE
The if-then-else statement – a branching method which chooses between two alternative
courses of action

Syntax:
IF (Boolean expression) THEN
statement1
ELSE
statement2 ; N.B. the semi-colon is placed after the statement
following the ELSE.

Eg.) The following piece of code checks the age of the person to see if he/she is eligible to vote.
The person must be 18 years and over to vote.

IF (age >= 18) THEN


writeln(‘You are eligible to vote’)
ELSE
writeln(‘You are too young to vote’);
IF...THEN...ELSE CONT’D
Eg.1) Write a program to read the score of a student in an examination and
determine whether the student has passed. If the score is greater than or equal to
50, the student has passed. Print whether the student has passed or failed.

Algorithm TestScore Program TestScore(input , output);


This algorithm determines whether a {This program determines whether a
student has passed of failed a test. student has passed or failed a test}
score – stores the student’s mark Var
score: integer;
Start Begin
Print (‘Please enter the score’) writeln(‘Please enter the score’);
Input Score readln(score);
IF Score >= 50 THEN IF score >= 50 THEN
Print ‘PASS’ writeln(‘PASS’)
ELSE ELSE
writeln(‘FAIL’);
Print ‘FAIL’
Stop End.
IF...THEN...ELSE CONT’D
Eg.2) Write a program which reads the age of a person and determine whether he/she is a
student. The person is considered a student if he/she is between the ages of 5 and 18. If the
person is under the age of 5 then he/she is a ‘toddler’. Otherwise, the person is an adult.
Print the age of the person.

Algorithm CheckAge Program CheckAge(input , output);

This algorithm prompts the user to input the age of a {This program prompts the user to input the age of a

person and prints whether he/she is a student, a person and prints whether he/she is a student, a

toddler or an adult toddler or an adult}

age – stores the age of the person var


age: integer;

Start Begin

Print(‘Please enter the age of the person’) writeln(‘Please enter the age of the person’;

Input(age) readln(age);

IF (age <= 18) AND (age >=5) THEN IF (age <= 18) AND (age >=5) THEN

Print(‘You are a student’) writeln(‘You are a student’)

ELSE IF (age < 5) THEN ELSE IF (age < 5) THEN

Print(‘You are a toddler’) writeln(‘You are a toddler’)

ELSE ELSE

Print(‘You are an adult’) writeln(‘You are an adult’);

Stop End.
EXERCISE #1
1. Code the algorithms from Exercise 2 in Pascal.
2. Write a program to request a score in a test and print a letter grade based on the
following:
score < 50 F
50 ≤ score ≤ 65 C
65 ≤ score < 80 B
score ≥ 80 A

3. Given 3 integer values representing the sides of a triangle, write a program to print:
⚫ Not a triangle – if the any of the values are negative or zero
⚫ Sorry !– if the length of any side is greater than or equal to the sum of the other
2 sides
⚫ Isosceles – if the triangle has two equal sides
⚫ Equilateral – if all three sides are the same
⚫ Scalene – if all three sides are different
THE ‘FOR’ LOOP
Eg.) A man works 40 hours per week and he is paid an hourly rate of $50.00 per
hour. Write a program to read the names and hours worked for 10 employees.
Determine and print their weekly wages along with their names.

ALGORITHM PASCAL CODE


Start Begin
FOR x = 1 to 10 DO FOR x = 1 to 10 DO
Print (‘Please enter a name and hours Begin
worked’) writeln(‘Please enter a name and
Input Name, Hours hours worked’);
Wage = Hours * 50 readln(Name, Hours);
Print (Name,’ $’,Wage) Wage = Hours * 50;
ENDFOR writeln(Name,’ $’,Wage);
Stop End;
End.
THE ‘WHILE’ LOOP
Eg.)Write Pascal code to accept an unspecified amount of integers. Calculate and
print the sum of the numbers entered. The program should be terminated when the
number 999 is entered.

Algorithm Pascal Code


Start Begin
Print(‘Please enter a number’) writeln(‘Please enter a number’);
Read(num) readln(num);
WHILE (num <> 999) DO WHILE (num <> 999) DO
sum = sum + num Begin
Print(‘Please enter a number’) sum:= sum + num;
Read (num) writeln(‘Please enter a number’);
ENDWHILE readln(num);
Print(‘The sum is: ‘, sum) End;
Stop writeln(‘The sum is: ‘, sum);
End.
THE ‘REPEAT...UNTIL’ LOOP
Eg.)Write Pascal code to accept an unspecified amount of integers. Calculate and
print the sum of the numbers entered. The program should be terminated when the
number 999 is entered.

Algorithm Pascal Code


Start Begin
Print(‘Please enter a number’) writeln(‘Please enter a number’);
Read(num) readln(num);
REPEAT REPEAT
sum = sum + num
sum:= sum + num;
Print(‘Please enter a number’)
writeln(‘Please enter a number’);
Read(num)
readln(num);
UNTIL (num = 999)
Print(‘The sum is: ‘, sum) UNTIL (num = 999);
Stop writeln(‘The sum is: ‘, sum);
End.
ARRAYS
An array is a structure which holds many variables, all of the same data type.
Each element of the array is capable of storing one piece of data (a variable). A
subscript is used to refer to a particular location.

Declaring an array
An array is usually declared in the ‘var’ section. The syntax is as follows:
Pseudocode: ArrayName[lower..upper] of data type
Pascal Code: ArrayName = Array[lower..upper] of data type

Eg.) numbers = Array[1..5] of integer;

Here is a visual representation of an array with 5 elements:

23 12 56 19 34
numbers[1] numbers[2] numbers[3] numbers[4] numbers[5]
INITIALISING ARRAYS
Pseudocode Pascal Code
Initialising an array of integers or real: Initialising an array of integers or real :
FOR x = 1 to n DO FOR x:= 1 to n DO
ArrayName[x] = 0 ArrayName[x] := 0;

Initialising an array of string: Initialising an array of string:


FOR x = 1 to n DO FOR x:= 1 to n DO
ArrayName[x] = ‘ ‘ ArrayName[x] := ‘ ‘;

Initialising an array of char: Initialising an array of char:


FOR x = 1 to n DO FOR x:= 1 to n DO
ArrayName[x] = ‘ ‘ ArrayName[x] := ‘ ‘;
INPUTTING/OUTPUTTING TO/FROM AN ARRAY

Pseudocode Pascal Code


Inputting data into an array: Inputting data into an array:
FOR x = 1 to n DO FOR x := 1 to n DO
Print(‘Please enter.......’) Begin
Read(ArrayName[x]) writeln(‘Please enter.....’);
EndFOR readln(ArrayName[x]);
End;

Outputting from an array: Outputting from an array:


FOR x = 1 to n DO FOR x := 1 to n DO
Print(ArrayName[x]) writeln(ArrayName[x]);
Eg 1.) Read in the marks of 10 students and store them in an array MARKS.
Calculate the sum an average of those numbers.

Algorithm Calculate Program Calculate;


This algorithm calculates the sum and average of {this program calculates the sum and average of
10 numbers using an array 10 marks using an array}
var
sum – holds the value of sum sum, n: integer;
average – holds the value of average average: real;
Marks[1..10] of integer – array of marks Marks = Array[1..10] of integer;

Start Begin
Set sum to 0 sum := 0;
FOR n = 1 to 10 DO FOR n := 1 to 10 DO
Print(‘Please enter a mark’) Begin
Read(Marks[n]) writeln(‘Please enter a mark’);
Set sum to sum + Marks[n] readln(Marks[n]);
EndFOR sum:= sum + Marks[n];
Set average to sum/10 end;
Print(‘The sum is: ‘, sum) average:= sum/10;
Print(‘The average is: ‘, average) writeln(‘The sum is: ‘, sum);
Stop writeln(‘The average is: ‘, average);
End.
SEARCHING AN ARRAY
The following is a standard algorithm for searching for a particular item in an array:

Set Found to 0
‘item’ can be an integer, character or a string and refers
FOR x = 1 to n DO to an element in an array which is to be located.
IF item = ArrayName[x] THEN
set Found to x
set x to n setting x to n ‘forces’ exit out of the FOR loop once the item is found

EndIF
EndFOR
IF (Found = 0) THEN
Print(item,’ is not found’)
ELSE
Print(item,’ is found in ‘, Found)
EndIF
Eg 2.) Read in the marks of 10 students and store them in an array MARKS.
Determine and print the maximum and minimum mark.
Program Calculate2;
{This program reads in the marks of 10 students and stores them in an array. It also
finds the maximum and minimum marks}
var
min, max, n: integer;
Marks = Array[1..10] of integer;
Begin
max := 0; min := 99999;
FOR n := 1 to 10 DO
Begin
writeln(‘Please enter a mark’);
readln(Marks[n]);
IF (Marks[n] > max) THEN
max := Marks[n];
IF (Marks[n] <main THEN
min := Marks[n];
End;
writeln(‘The maximum mark is: ‘, max);
writeln(‘The minimum mark is: ‘, min);
End.
EXERCISE #2
Consider the following array of integers:

10 7 12 8 26 19 21
1 2 3 4 5 6 7

1. Write code to declare the above array of marks.


2. What is the contents of Marks[4]?
3. Draw a diagram to illustrate how the contents of Marks[3] and Marks[6] can be
exchanged.
4. Write code to:
i. Swap the contents of Marks[3] and Marks[6]. Use a temporary variable called
‘temp’
ii. Increase each mark by 10%
iii. Print each of the marks that is greater than 20
PROCEDURES
Procedures are sub-programs that can be called from the main part of the program.
Procedures are declared outside of the main program body using the procedure
keyword. Procedures must also be given a unique name. Procedures have their own
begin and end.

Program Procedures;

Procedure Hello;
Begin
Writeln('Hello');
End;

{Main Program}
Begin
Hello;
End.
Eg 3.)Using Eg.2, re-write the program using procedures.

Program Calculate3; Procedure Determine;


{This program finds the max and min of 10 {This procedure searches the array element
marks which have been read into an array} element until the max and min marks are
Var found}
min, max, n: integer; Begin
Marks = Array[1..10] of integer; FOR n := 1 to 10 DO
Begin
Procedure Initialise; InputData;
{This procedure initialises all variables used} IF (Marks[n] > max) THEN
Begin max := Marks[n];
max := 0; min := 99999; IF (Marks[n] <main THEN
End; min := Marks[n];
End; {FOR}
Procedure InputData; End;
{This procedure reads the data into the array}
Begin
writeln(‘Please enter a mark’);
readln(Marks[n]);
End;
Procedure OutputData;
{This procedure outputs the data on the screen}
Begin
writeln(‘The maximum mark is: ‘, max);
writeln(‘The minimum mark is: ‘, min);
End;

{Main Program}
Begin
Initialise;
Determine;
OutputData;
End.

EXERCISE #3
Using Exercise #2, write each part of Q4 as separate procedures and incorporate them into
a single program.

You might also like