pascal programming. introduction pascal is a programming language named after the 17th century...

31
PASCAL PROGRAMMING

Upload: ambrose-gregory

Post on 18-Jan-2016

292 views

Category:

Documents


20 download

TRANSCRIPT

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

PASCAL PROGRAMMING

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

INTRODUCTIONPASCAL 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.

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

KEYWORDS AND IDENTIFIERS

Keywords are reserved words, i.e. You cannot use keywords to describe

variables. Some examples include:

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

Program Begin End If Else

While Do Repeat Until For

Const Var Procedure Function Then

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

VARIABLESA 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

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

INPUT, PROCESS & OUTPUTThe majority of programs will follow the Input - Process - Output cycle.

INPUTIn 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.

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

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

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

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);

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

SYNTAXSyntax 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

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

PROGRAM STRUCTURENearly 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);

Begin

writeln(‘Hello. How are you?’);

End.

Program AddNumbers(input,output);Var a,b,sum:integerBegin a:=2; b:=5; sum:= a + b; writeln(‘The sum is: ‘,sum);End.

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

COMMENTSComments 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.

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

CONVERTING PSEUDOCODE TO PASCAL CODE

ALGORITHM

Algorithm Welcome

This algorithm prints a welcome message for

the user

Start

Print (‘Welcome to the world of problem- solving !’)

Stop

PASCAL CODE

Program Welcome;

{This program prints a welcome message for

the user}

Begin

writeln(‘Welcome to the world of problem-

solving!’);

End.

Eg. 1) Write an program which prompts the user to input his/her name and prints a welcomemessage to the user.

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

CONVERTING PSEUDOCODE TO PASCAL CODE CONT’D

Algorithm FindAverage

This algorithm finds the total and average of

3 numbers which the user inputs.

num1,num2,num3 – stores the 3 numbers

sum – stores the sum of the 3 numbers

average – stores the average of the 3 numbers

Start

Set num1,num2,num3 to 0

Print(‘Please enter 3 numbers’)

Input (num1,num2,num3)

sum = num1+num2+num3

average = Sum/3

Print(‘The sum is: ‘,sum)

Print(‘The average is: ‘,average)

Stop

Program FindAverage(input,output);

{This program finds the total and average

of 3 numbers which the user inputs}

Var

num1, num2, num3, Sum: integer;

Average: real;

Begin

num1:=0; num2:=0; num3:=0;

writeln(‘Please enter 3 numbers’);

readln(num1,num2,num3);

sum:= num1+num2+num3;

average:= sum/3;

writeln(‘The sum is: ‘,sum);

writeln(‘The average is: ‘,average:4:2);

End.

Eg. 2) Write a program to prompt the user to input 3 numbers and calculate and print the total and average

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

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.

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

EXERCISE 51. 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.

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

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) THENwriteln(‘You are eligible to vote’)

ELSEwriteln(‘You are too young to vote’);

IF...THEN...ELSE

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

IF...THEN...ELSE CONT’DEg.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

This algorithm determines whether a

student has passed of failed a test.

score – stores the student’s mark

Start

Print (‘Please enter the score’)

Input Score

IF Score >= 50 THEN

Print ‘PASS’

ELSE

Print ‘FAIL’

Stop

Program TestScore(input , output);

{This program determines whether a student has passed or failed a test}

Var

score: integer;

Begin

writeln(‘Please enter the score’);

readln(score); IF score >= 50 THEN

writeln(‘PASS’) ELSE

writeln(‘FAIL’);

End.

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

IF...THEN...ELSE CONT’D

Algorithm CheckAge

This algorithm prompts the user to input the age of a

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

toddler or an adult

age – stores the age of the person

Start

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

Input(age)

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

Print(‘You are a student’)

ELSE IF (age < 5) THEN

Print(‘You are a toddler’)

ELSE

Print(‘You are an adult’)

Stop

Program CheckAge(input , output);

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

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

toddler or an adult}

var

age: integer;

Begin

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

readln(age);

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

writeln(‘You are a student’)

ELSE IF (age < 5) THEN

writeln(‘You are a toddler’)

ELSE

writeln(‘You are an adult’);

End.

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.

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

EXERCISE #11. 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

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

THE ‘FOR’ LOOPEg.) 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

Start

FOR x = 1 to 10 DO

Print (‘Please enter a name and hours

worked’)

Input Name, Hours

Wage = Hours * 50

Print (Name,’ $’,Wage)

ENDFOR

Stop

PASCAL CODE

Begin

FOR x = 1 to 10 DO

Begin

writeln(‘Please enter a name and

hours worked’);

readln(Name, Hours);

Wage = Hours * 50;

writeln(Name,’ $’,Wage);

End;

End.

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

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

Start

Print(‘Please enter a number’)

Read(num)

WHILE (num <> 999) DO

sum = sum + num

Print(‘Please enter a number’)

Read (num)

ENDWHILE

Print(‘The sum is: ‘, sum)

Stop

Pascal Code

Begin

writeln(‘Please enter a number’);

readln(num);

WHILE (num <> 999) DO

Begin

sum:= sum + num;

writeln(‘Please enter a number’);

readln(num);

End;

writeln(‘The sum is: ‘, sum);

End.

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

THE ‘REPEAT...UNTIL’ LOOPEg.)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.

AlgorithmStartPrint(‘Please enter a number’)Read(num)REPEAT

sum = sum + num Print(‘Please enter a number’) Read(num)

UNTIL (num = 999)Print(‘The sum is: ‘, sum)Stop

Pascal Code

Begin

writeln(‘Please enter a number’);

readln(num);

REPEAT

sum:= sum + num;

writeln(‘Please enter a number’);

readln(num);

UNTIL (num = 999);

writeln(‘The sum is: ‘, sum);

End.

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

ARRAYSAn 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:

numbers[1] numbers[2] numbers[3] numbers[4] numbers[5]

23 12 56 19 34

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

INITIALISING ARRAYS

Pseudocode Pascal Code

Initialising an array of integers or real:

FOR x = 1 to n DO

ArrayName[x] = 0

Initialising an array of string:

FOR x = 1 to n DO

ArrayName[x] = ‘ ‘

Initialising an array of char:

FOR x = 1 to n DO

ArrayName[x] = ‘ ‘

Initialising an array of integers or real :

FOR x:= 1 to n DO

ArrayName[x] := 0;

Initialising an array of string:

FOR x:= 1 to n DO

ArrayName[x] := ‘ ‘;

Initialising an array of char:

FOR x:= 1 to n DO

ArrayName[x] := ‘ ‘;

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

INPUTTING/OUTPUTTING TO/FROM AN ARRAY

Pseudocode Pascal Code

Inputting data into an array:

FOR x = 1 to n DO

Print(‘Please enter.......’)

Read(ArrayName[x])

EndFOR

Outputting from an array:

FOR x = 1 to n DO

Print(ArrayName[x])

Inputting data into an array:

FOR x := 1 to n DO

Begin

writeln(‘Please enter.....’);

readln(ArrayName[x]);

End;

Outputting from an array:

FOR x := 1 to n DO

writeln(ArrayName[x]);

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

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

This algorithm calculates the sum and average of

10 numbers using an array

sum – holds the value of sum

average – holds the value of average

Marks[1..10] of integer – array of marks

Start

Set sum to 0

FOR n = 1 to 10 DO

Print(‘Please enter a mark’)

Read(Marks[n])

Set sum to sum + Marks[n]

EndFOR

Set average to sum/10

Print(‘The sum is: ‘, sum)

Print(‘The average is: ‘, average)

Stop

Program Calculate;

{this program calculates the sum and average of

10 marks using an array}

var

sum, n: integer;

average: real;

Marks = Array[1..10] of integer;

Begin

sum := 0;

FOR n := 1 to 10 DO

Begin

writeln(‘Please enter a mark’);

readln(Marks[n]);

sum:= sum + Marks[n];

end;

average:= sum/10;

writeln(‘The sum is: ‘, sum);

writeln(‘The average is: ‘, average);

End.

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

The following is a standard algorithm for searching for a particular item in an array:

Set Found to 0

FOR x = 1 to n DO

IF item = ArrayName[x] THEN

set Found to x

set x to n

EndIF

EndFOR

IF (Found = 0) THEN

Print(item,’ is not found’)

ELSE

Print(item,’ is found in ‘, Found)

EndIF

SEARCHING AN ARRAY

‘item’ can be an integer, character or a string and refers to an element in an array which is to be located.

setting x to n ‘forces’ exit out of the FOR loop once the item is found

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

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.

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

EXERCISE #2Consider the following array of integers:

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

10 7 12 8 26 19 21

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

PROCEDURESProcedures 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.

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

Eg 3.)Using Eg.2, re-write the program using procedures.

Program Calculate3;

{This program finds the max and min of 10

marks which have been read into an array}

Var

min, max, n: integer;

Marks = Array[1..10] of integer;

Procedure Initialise;

{This procedure initialises all variables used}

Begin

max := 0; min := 99999;

End;

Procedure InputData;

{This procedure reads the data into the array}

Begin

writeln(‘Please enter a mark’);

readln(Marks[n]);

End;

Procedure Determine;

{This procedure searches the array element

element until the max and min marks are

found}

Begin

FOR n := 1 to 10 DO

Begin

InputData;

IF (Marks[n] > max) THEN

max := Marks[n];

IF (Marks[n] <main THEN

min := Marks[n];

End; {FOR}

End;

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

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 #3Using Exercise #2, write each part of Q4 as separate procedures and

incorporate them into

a single program.