Algorithm and Pascal Conversion Notes Sheet Revised
Algorithm and Pascal Conversion Notes Sheet Revised
No matter how simple or complex the problem, it must be defined to remove all doubts as to
what solution is required. Ideally the problem should be defined that it can be interpreted to have
only one meaning; however this is not always the case.
To understand the problem, sometimes it is necessary to read the problem a few times. Then the
problem must be broken down into small components corresponding to different activities and
operations.
Search the problem to determine what input is needed to solve the problem. If no input is stated
that does not mean that no input is needed. If input is required, then it must be entered in the
computer.
Determine if calculations are required. If calculations are required, then determine what type of
calculations. Are they additions, subtractions, multiplications, divisions, percentages or a
combination of these?
We can do all this using the techniques we learn in this chapter. The focus here is to learn about
statements that alter the execution of a program based on the programs input parameters. These
statements are called conditional statements. There are two basic forms, the IF-THEN statement
and the CASE statement.
A boolean expression is an expression whose value returns either TRUE or FALSE. A trivial
boolean expression is TRUE or FALSE.
IF …..THEN
Function:
The IF - THEN statement allows you to have the machine ask a true/false question and if the
answer is true, perform one or more statements.
This construct provides two paths for selection. A path called the THEN path and a path
called the ELSE path.
The THEN path is made up of instructions between the word THEN and the word ELSE.
The ELSE path is made up of instructions between the word ELSE and ENDIF. marks the
end of the last path
Input the age of the person. If the age is greater than 35 output “old person”
otherwise output “young person”
READ AGE
IF AGE > 35 THEN
PRINT “old person”
ELSE
PRINT “young person”
ENDIF
When developing the algorithm for some problems it may appear that the IF-THEN construct
should be used instead of the IF-THEN-ELSE construct.
The start value of the count variable is 0. Counting begins as soon as the counter instructions
<Count Variable> = <Count Variable > + 1 is executed. After executing the first entry to be
counted, a count of 1 will be the result. On this basis, even though one entry may be involved,
an algorithm can be developed to show the count.
CUMULATIVE TOTALS
Cumulative total is a progressive total that is arrived at by adding a value to the current total to
obtain a new total.
The Cumulative total is stored in a variable. The variable is assigned a start value of 0 and as
each value is added, a new cumulative total results. The instructions that form the cumulative
total system are:
The variable to be totalled could be a variable which is READ or a variable in which a value was
assigned.
E.G. TOTAL = 0
READ PRICE, QTY
AMOUNT = PRICE * QTY
TOTAL = TOTAL + AMOUNT
PRINT “TOTAL”, TOTAL
IT 2016 NOTES (SKY) 4
REPETITION / Iterations
The solution to many problems require performing some of the instructions more than once.
This is necessary if the same activity is done more than once. Instructions to be repeated are
called a loop. There are three types of loop.
(1) A loop which involves repeating the instructions a predetermine number of times
FOR Construct
(2) A loop which involves repeating the instructions for an indefinite number of times
WHILE Construct
(3) A loop that repeats until a predefined condition is met is called a REPEAT…
UNTIL
WHILE CONSTRUCT
The initial value for the condition can be stored in a variable which is read or it can be a value
which is assigned to the variable.
E.G. READ A
A=1
This initial value is necessary so that the comparison for the condition can be made when the
WHILE instruction is executed the first time.
The condition is made of the said variable which stores the initial value called the loop variable,
an operator>, <,>=, <=, <> and a termination constant.
The instruction which contains the WHILE statement is to be interpreted to mean the following:
1. Repeat the instructions that fall between WHILE and END WHILE as long as
the condition is true. When the condition is false, the repetition ceases and any
instructions following the END WHILE statements are then executed.
2. An essential requirement when using the WHILE construct is that within the
WHILE – END WHILE statements, an instruction which changes the value of
the loop variable must be present. This instruction causes the loop to be
terminated. If the instruction is not present, the instructions of the loop will be
repeated forever.
3. The instruction for changing the value of the loop variable could be either an
input statement or an instruction within the loop which assigns a value to the loop
variable.
E.G.
Write an algorithm to calculate and print the average of three (3) scores for a number of
students terminated by 999
FOR is the beginning and END FOR the end of the loop. The loop variable is used to count the
number of times the loop is executed. The value of this variable starts at the beginning value and
is increased by one (1) each time the loop is executed unless otherwise directed by the STEP
clause.
The STEP clause indicates how much the loop variable is to increased by each time the loop is
executed. The STEP clause is not necessary if the increment is (1). Use the (-) minus sign with
the increment value to decrease the loop variable value.
When the end value is reached, the loop terminates and the instruction following ENDFOR is
then executed.
The beginning, ending and increment values can be constant or variables. Variables give greater
flexibility for altering the number of times for repeating the loop. When variables are used the
said variable must be read as input before the FOR instruction is encountered.
E.G.
Write an algorithm to calculate and print the average score for each student in a class of
25. Each student was given 3 tests.
FOR S = 1 TO 25 DO
READ SCOREA, SCOREB, SCOREC
SUM SCOREA+ SCOREB+ SCOREC
AVERAGE Sum / 3
PRINT “Average” AVERAGE
ENDFOR
Each column has a title which describes the information in the column. Tables are developed
using the FOR loop.
Data entry which is needed to generate the table must be read prior to printing the column titles
and column titles must be printed before starting the FOR loop. This is necessary to avoid
having data entry or column titles printed within the table information.
E.G.
Print a table of numbers which funs from 1 to 10 and the corresponding square for each
number.
TRACE TABLES
A Trace table is a table which is completed by tracing the instructions in the algorithm with
given data to arrive at solutions
E.G. B=2 N D E
C= N 1
FOR N = 1 to 5 DO 2
D =N* B 3
E=N*C 4
ENDFOR 5
1. Before developing the algorithm, determine if one (1) or more of the following systems
are required: -
(a) IF
(b) WHILE
(c) FOR
(d) COUNT
(e) CUMULATIVE
2. Some algorithms do not require the use of any of the listed systems.
3. When one or more entries have to be counted or totalled separately, IF must be used to
select the correct counter or cumulative system for each entry.
4. Counting is necessary:
When the average is desired and the number to divide by is unknown.
To determine the number of occurrence of an event or entity.
WRITING PROGRAMS
About Pascal
The Pascal programming language was created by Niklaus Wirth in 1970. It was named after
Blaise Pascal, a famous French Mathematician. It was made as a language to teach programming
and to be reliable and efficient. Pascal has since become more than just an academic language
and is now used commercially.
Var
variableName : Datatype; {Declaration}
Begin
Statements; {Executable Statements}
End.
We always start a program by typing its name. Type Program and the name of the program next
to it. We will call our first program "Hello" because it is going to print the words "Hello world"
on the screen. The words input and output are used to indicate that the program will accept input
and produce output, respectively.
Next we will type begin and end. We are going to type the main body of the program between
these 2 keywords. Remember to put the full stop after the end.
Begin
End.
(input, output) states what the program will do, ie, input and/or output data. Data is inputted
from the keyboard, and outputted to the console screen.
Begin defines the starting point of the program, and provides a means of grouping statements
together (ie all statements between a begin and end are considered part of the same group or
block).
program statements are commands or instructions to the computer which perform various tasks.
WRITELN
Syntax:
You will see that the "Hello world" is between single quotes. This is because it is what is called a
string. All strings must be like this. The semi-colon at the end of the line is a statement separator.
You must always remember to put it at the end of the line.
Writeln is just like Write except that it moves the cursor onto the next line after it has printed the
words. Here is a program that will print "Hello" and then "world" on the next line:
BEGIN
Writeln('Hello');
Write('world');
Readln;
End.
If you want to skip a line then just use Writeln by itself without any brackets.
READLN
Function:
The READLN statement tells the computer get information and put it into storage locations. This
section talks about reading from the keyboard, but READLN can also from a disk file. The
READLN statement and the assignment statement are the only two Pascal statements that can
change the contents of a storage location.
Syntax:
The Readln command will now be used to wait for the user to press enter before ending the
program.
The readln statement discards all other values on the same line, but read does not. In the
previous program, replacing the read statements with readln and using the same input, the
program would assign 237 to numb1, discard the value 64, and wait for the user to enter in
another value which it would then assign to numb2.
Program Hello;
BEGIN
Write('Hello world');
Readln;
end.
Displaying information
Program Lesson2_Program1;
Var name, surname: String;
Begin
Readln;
End.
Comments
Comments are things that are used to explain what parts of a program do. Comments are ignored
by the compiler and are only there for the people who use the source code. Comments must be
put between curly brackets{ }. You should always have a comment at the top of your program to
say what it does as well as comments for any code that is difficult to understand. Here is an
example of how to comment the program we just made:
{This program will clear the screen, print "Hello world" and wait for
the user to press enter.}
Program Hello;
BEGIN
ClrScr;{Clears the screen}
Write('Hello world');{Prints "Hello world"}
Readln;{Waits for the user to press enter}
END.
Indentation
You will notice that I have put 3 spaces in front of some of the commands. This is called
indentation and it is used to make a program easier to read. A lot of beginners do not understand
the reason for indentation and don't use it but when we start making longer, more complex
programs, you will understand.
Every Pascal program must follow a basic structure. Below is the basic structure that every
Pascal program must follow.
PROGRAM ProgramName;
VAR
VariableName : VariableType;
VariableName : VariableType;
...
BEGIN
the main program block. It should be small and all
work should be delegated to the procedures and
functions.
END.
Byte 0 to 255
Word 0 to 65535
ShortInt -128 to 127
Integer -32768 to 32767
LongInt -4228250000 to 4228249000
Real floating point values
Char 1 character
String up to 255 characters
Boolean true or false
Assignment
The assignment statement is the only statement in Pascal that does not have a key word. It is
recognized by the assignment operator ( := )
Function:
Places a value in a storage location. Allows calculations to be performed.
Syntax:
The only thing allowed on the left side of the assignment operator is the name of a
storage location.
No space is allowed between the colon and the equal sign.
An expression can be:
1. a constant:
X := 5;
2. a variable name:
temp := size;
3. an arithmetic calculation:
IT 2016 NOTES (SKY) 14
sum := a + b;
total := total + 1;
average := ( x + y + z) / 3;
value_indicator := new_value * scale_factor;
You can create 2 or more variables of the same type if you separate their names with commas.
You can also create variables of a different type without the need for another var statement.
Program Variables;
var
i, j: Integer;
s: String;
BEGIN
End.
When you assign a value to a string variable, you must put it between single quotes.
Strings hold characters. Characters include the the letters of the alphabet as well as special
characters and even numbers. It is important to understand that integer numbers and string
numbers are different things. You can add strings together as well.
Constants
Constants are like variables except that their values can't change. You assign a value 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.
Program Variables;
const
pi: Real = 3.14;
var
c, d: Real;
BEGIN
d := 5;
IT 2016 NOTES (SKY) 15
c := pi * d;
End.
Outputting Real
"fieldwidth" is not different from the one explained in the format of an integer. However,
precision is something new. Precision defines the number of digits after the decimal point. If
fieldwidth is not defined, scientific notation is used and the number of digits after the decimal
point depends on fieldwidth. If both precision and fieldwidth are not specified, a default will be
used.
Arithmetic Operators
Following table shows all the arithmetic operators supported by Pascal. Assume variable A holds
10 and variable B holds 20, then −
Show Examples
Operator Precedence
The following precedence table applies to Real and Integer operators. Parentheses always have
the highest priority, and operators of equal priority are always performed left to right.
Priority Operation
First * / DIV MOD
Second + -
For example: To evaluate 4.0 + 6.0 * 3.0, you must follow the precedence table and perform the
multiplication first, and the addition second. Hence, evaluating this expression will always give
an answer of 22.0. If you want to perform the addition first, you must include the 4.0 + 6.0
within parentheses: (4.0 + 6.0) * 3.0.
7 / 3 = 2.3333, but 2.3333 is not an Integer. Hence, we need a method of doing division that only
results in Integer values. For this we use MOD and DIV:
Boolean Operators
Following table shows all the Boolean operators supported by Pascal language. All these
operators work on Boolean operands and produce Boolean results. Assume variable A holds true
and variable B holds false, then −
Show Examples
Colours
To change the color of the text printed on the screen we use the TextColor command.
Program Colors;
uses
crt;
IT 2016 NOTES (SKY) 17
begin
TextColor(Red);
Writeln('Hello');
TextColor(White);
Writeln('world');
end.
Decisions
Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages −
Pascal programming language provides the following types of decision making statements.
Click the following links to check their detail.
Statement Description
if - then statement An if - then statement consists of a boolean expression followed by
one or more statements.
If-then-else statement An if - then statement can be followed by an optional else
statement, which executes when the boolean expression is false.
nested if statements You can use one if or else if statement inside another if or else if
statement(s).
case statement A case statement allows a variable to be tested for equality against a
list of values.
If Then Else
The if statement allows a program to make a decision based on a condition. The following
example asks the user to enter a number and tells you if the number is greater than 5:
Program Decisions;
var
i: Integer;
BEGIN
Writeln('Enter a number');
Readln(i);
if i > 5 then
Writeln('Greater than 5');
End.
The above example only tells you if the number is greater than 5. If you want it to tell you that it
is not greater than 5 then we use else. When you use else you must not put a semi-colon on the
end of the command before it.
Program Decisions;
var
i: Integer;
BEGIN
Writeln('Enter a number');
Readln(i);
if i > 5 then
Writeln('Greater than 5')
else
Writeln('Not greater than 5');
End.
program Decisions;
var
i: Integer;
BEGIN
Writeln('Enter a number');
Readln(i);
if (i > 1) and (i < 100) then
Writeln('The number is between 1 and 100');
End.
If you want to put 2 or more commands for an if statement for both the then and the else parts
you must use begin and end; to group them together. You will see that this end has a semi-colon
after it instead of a full stop.
Program Decisions;
var
i: Integer;
BEGIN
Writeln('Enter a number');
Readln(i);
if i > 0 then
begin
Writeln('You entered ',i);
Writeln('It is a positive number');
end;
END.
Program Decisions;
var
i: Integer;
BEGIN
Writeln('Enter a number');
Readln(i);
if i > 0 then
Writeln('Positive')
else
if i < 0 then
Writeln('Negative')
else
Writeln('Zero');
END.
Repeat a statement or a group of statements a specified number of times. (The FOR statement
does a lot of things, so its syntax and operation have a lot of steps.)
Syntax:
FOR i := 1 to 5 DO
BEGIN
statement;
----
statement;
END;
The assignment may be any legal assignment statement. The variable on the left of the
assignment operator is sometimes called the control variable. It must be an integer.
The expression can be any expression (remember an expression is the sort of thing legal on
the right of an assignment operator.) It should have an integer value.
Following the DO may be either a single statement or a number of statements in a BEGIN --
END block.
The for loop uses a loop counter variable, which it adds 1 to each time, to loop from a first
number to a last number.
Program Loops;
var
i: Integer;
BEGIN
for i := 1 to 10 do
Writeln('Hello');
END.
If you want to have more than 1 command inside a loop then you must put them between a begin
and an end.
Program Loops;
var
i: Integer;
BEGIN
IT 2016 NOTES (SKY) 21
for i := 1 to 10 do
begin
Writeln('Hello');
Writeln('This is loop ',i);
end;
END.
While loop
Function:
Lets us repeat a statement or a group of statements over and over testing a condition before each
repetition to see if we should stop. This group of code repeated over and over is called a loop.
Syntax:
WHILE condition DO
BEGIN
statement;
------
statement;
END;
Syntax:
REPEAT
statement(s)
UNTIL condition;
There may be any number of statements between the REPEAT and the UNTIL. No BEGIN -
END block is required if you want more than one statement.
The condition is any legal condition.
Operation:
1. The statements between the REPEAT and the UNTIL are performed.
2. The condition following the UNTIL is tested.
3. If the condition is false, control passes to the first statement following the REPEAT and
the operation continues as step 1).
If the condition is true, control passes to the statement following the UNTIL
The repeat until loop is like the while loop except that it tests the condition at the bottom of the
loop. It also doesn't have to have a begin and an end if it has more than one command inside it.
program Loops;
var
i: Integer;
begin
i := 0;
repeat
i := i + 1;
Writeln('Hello');
until i = 10;
end.
If you want to use more than one condition for either the while or repeat loops then you have to
put the conditions between brackets.
program Loops;
var
i: Integer;
s: String;
begin
i := 0;
repeat
i := i + 1;
Write('Enter a number: ');
Readln(s);
until (i = 10) or (s = 0);
end.
Selection Statements
If-Then
Example
if (x > y) then
begin
Write(‘The larger value is:’,
x);
end;
If-Then-Else
Example
if (x > y) then
begin
Write (‘The larger value is:’ ,
x);
end
else
begin
Write (‘The larger value is:’ ,
y);
end;
For Iteration
Format
For variable = start to end Do
begin
Block of Statements;
end;
Example
For k := 1 to 100 do
Begin
Read(name);
Read(age);
end;
While Iteration
Format
Read (variable);
While condition do
begin
Block of statements;
IT 2016 NOTES (SKY) 24
IT 2016 NOTES (SKY) 25