Algorithm BasicsFinal
Algorithm BasicsFinal
Algorithm BasicsFinal
Table of contents
3
Syllabus
4
Syllabus
I-
Syllabus
1. Overview of algorithm
2. Objects and data types
3. Sequencing, operators and base instructions
4. Control structures
5. Arrays
6. Some bases algorithms
7. Procedure and Functions
8. Records and Files
5
Chapter 1:
II-
II
Overview on
algorithms
Introduction
A computer engineer is expected to tackle any given problem in the most efficient
manner. This efficiency can be in terms of memory or time or both. However,
efficiency becomes important only if the solution, proposed by the person, solves
the problem. The steps followed to do so constitute an algorithm. This chapter
introduces the concept of algorithm, discusses the ways of writing an algorithm,
and explores the basics of algorithmic designing. We start with the informal
definition of an algorithm.
Definition : Algorithm
Algorithm refers to the steps to be carried out in order to accomplish a particular
task.
Algorithms are used everywhere, from a coffee machine to a nuclear power plant. A
good algorithm should use the resources such as the CPU usage, time, and memory
judiciously. It should also be unambiguous and understandable. The output
produced by an algorithm lies in a set called range. The input, is taken from a set
‘domain' (input constraints). From the domain only the values satisfying given
constraints can be taken. These constraints are referred to as input constraints.
Input constraints determine the values of xi, i.e., input. The inputs are related to
each other as governed by relation corresponding to the task that is to be
accomplished. This is referred to as explicit constraint.
1. Overview
7
Chapter 1: Overview on algorithms
8
Chapter 1: Overview on algorithms
Definition
An algorithm is a sequence of steps in order to carry out a particular task.
It can have zero or more inputs.
It must have at least one output.
It should be efficient both in terms of memory and time.
It should be finite.
Every statement should be unambiguous.
The meaning of finite is that the algorithm should have countable number of steps.
It may be stated that a program can run infinitely but an algorithm is always finite.
However, Algorithm 1.1, in spite of being simple, is not commonly used. The
flowchart or a pseudocode is more common as compared to ‘English-like algorithms'
9
Chapter 1: Overview on algorithms
10
Chapter 1: Overview on algorithms
11
Chapter 1: Overview on algorithms
12
Chapter 1: Overview on algorithms
13
Chapter 1: Overview on algorithms
A. Algorithmic approach
Definition : Algorithm
An algorithm is an ordered sequence of operations to obtain a definite result in
finite time. The reason for an algorithm is to solve a problem. The greatest
attention must be paid to understanding the problem to be solved, which is the
most critical step in the design of an algorithm. Algorithmics is the science that
studies algorithms. It allows to :
Describe a methodical approach to programming,
Master the complexity,
Ensure easy maintenance,
Lower the costs, ...
Have you ever opened a cookbook?
Have you ever pointed the way to a lost tourist?
Have you ever search an item for someone by phone?
If yes, without knowing it, you have already run an algorithm.
Like what, the algorithm is not a mysterious knowledge reserved for a few rare
initiates touched by the divine grace, but an aptitude shared by the totality of the
humanity.
Once executed correctly, an algorithm leads to a given result. So, if an algorithm is
right, its result will be the desired or expected result. On the other hand, if an
algorithm is false, the result will be if it can be said random.
A good algorithm must be:
Readable: the algorithm must be understandable even by a non-computer
scientist
Always ends: the algorithm must have an end
Accurate and unambiguous: each element of the algorithm should not be
confusing
Concise: An algorithm must not exceed one page. If this is the case, it is
necessary to split the problem into several sub-problems.
Structured: an algorithm must consist of different easily identifiable parts.
Solve the problem.
Let us define below all the elementary operations to be performed between the
moment the alarm rings and the moment when we go out to work.
14
Chapter 1: Overview on algorithms
Simulator
We can see in this example that the order of operations is important. Indeed, it
would be very embarrassing to invert actions 2 and 4 or actions 4 and 5.
Suppose then that this sequence of instructions is described by a person in
possession of an umbrella. Thus, it would be necessary to envisage a structuring of
the continuation of the operations allowing him to take his umbrella or coat only in
the event that it rained. For this, we must have an alternative structure to make a
choice. Likewise, if this person has to respect these same gestures every day until,
for example, they are on holiday, we must have an iterative or repetitive structure
to respect this sequence of actions until the awakening do not ring anymore.
Method : Principe
Before developing an algorithm, it is necessary to:
Understand the nature of the problem and specify the data to be provided
(inputs).
Specify the results you want to obtain (outputs).
Determine the process of transforming data into results.
In algorithmic, each elementary task is described by a simple and understandable
expression (or word).
Given: A, B
Result: X
Process: Determine X in AX + B = 0 according to the different possible cases.
15
Chapter 1: Overview on algorithms
16
Chapter 1: Overview on algorithms
Conclusion
Throughout this lesson, we were talking about introducing the notion of algorithm,
giving the characteristics of an algorithm and giving the algorithm development
process. Life is only algorithmic and thanks to the algorithms, the man finds the
solutions to his problems if the algorithm is well elaborated.
17
OBJECT AND TYPE
III -
III
OF DATA
Object
The universe of objects of a treatment is finished. It is therefore possible to fully
and unambiguously describe an object. The processing of an object concerns the
value of this object. If this value can not be changed, we are talking about constant
otherwise we are talking about variable. An object is perfectly defined if we know
its name (its identifier), its type and its value.
Types
There are two main advantages:
To describe the objects of the same nature and admitting the same
operations, it suffices to have defined the type once and for all and to
indicate for a given type, the list of associated objects; we avoid painful
repetitions.
There is a way to detect a number of errors without running the program
simply by examining object operations and checking that they are legal.
19
OBJECT AND TYPE OF DATA
x NOT(x)
20
OBJECT AND TYPE OF DATA
TRUE FALSE
FALSE TRUE
Table 2 NOT(x)
x y xORy
x y xANDy
Object statement
Constant
To declare a constant, we must specify in the declaration part of the constants its
name and its value. The syntax is as follows:
Const identifier = value;
where value refers to one of the base type values.
The identifier thus defined has the type to which the value belongs. The identifier is
composed of letters or numbers. It must obligatorily start with a letter.
Example:
Const PI = 3.14;
EPSI = 0.000042;
WHITE = '';
Variable
To declare a variable, one must specify in the variable declaration part its name, its
type and possibly its value.
The declaration syntax is as follows:
Var identifier: type; or var identifier = value: type; or type is one of the basic
types and identifier is the name given to the variable.
21
SEQUENCING,
IV-
IV
OPERATORS AND
BASIC
INSTRUCTIONS
Sequencing
To analyze a problem is to look for the different steps necessary to solve it. To do
this, it is divided into sub-problems that will be executed one after the other, that is
to say, sequentially. The sub-problem decomposition is made until a series of
atomic elementary processes is obtained. These elementary processes are called
instructions.
The decomposition of a problem P into sub-problems P1, P2, P3 is done by
separating the sub-treatments by the character "; ". The start and end keywords
are used to delimit the processing.
A description of an algorithm with sequential processing can be given by the
following example:
1 Algorithm example;
2 Declaration of objects;
3 begin
4 If (condition) then
5 begin
6 P1;
7 P2;
8 P3;
9 end
10 endif
11 end
Basic instruction
a) Display
The writing order will be given by the instruction write. The syntax is: write
(exp1, exp2, exp3, ..., expn) where expi can represent an expression, a
character, a string, ...
The different values of the expi expressions are displayed one after the other in the
order indicated. Note that these sequences are separated by commas (,) and not by
semicolons (;).
Example:
write ('The square of 4 is', 4 * 4); will produce: The square of 4 is 16.
23
SEQUENCING, OPERATORS AND BASIC INSTRUCTIONS
b) comment
to improve the readability of an algorithm, we can use comments:
A comment is a sequence of characters framed by co and fco.
1 Algorithm compute_disk_area;
2 Const PI = 3.14; co value of PI fco
3 Var radius = 1.24; co fco radius value
4 begin
5 Co this algorithm calculates and displays the area of a disc of
radius 1.24 fco
6 Write ('The area of the radius disc', radius, 'is', PI * radius *
radius);
7 End
This algorithm displays: The area of the radius disc 1.24 is 3.8936.
c) variables
When a T-treatment is decomposed into sub-treatments T1, T2, ...; it is common
for the Ti subprocessing to use, for example, the intermediate result produced by a
Tj. These intermediate results r1, r2, ... that lead to a result r do not often need to
be preserved. Rather than designate them all by different constraints, we choose to
designate them by the successive values of the same object called variable. Thus, a
variable appears as a box whose contents can be modified during the execution of
the algorithm by the assignment instruction. The contents of this box is called the
value of the variable. A variable must be designated by a name or an identifier in
order to be identified.
The syntax is as follows:
Var identifier: type;
Or type designates one of the basic types;
Identifier is the name given to the variable
Note 1: We can factor the declaration of several variables of the same type by
separating them by commas
Note 2: The choice of the identifier must be judicious and evoke as much as
possible the role played by this variable. This choice is not always sufficient, we can
specify the role of the variable by a comment.
Example var x, y: real; co coordinates of a dot fco
d) Allocation or assignment
The assignment statement has the effect of modifying the value contained in a
variable. The syntax is as follows:
Identifier: = expression; or identifier<-expression;
where the symbols ": =" or "<-" represents the assignment symbol
Note: The expression must be of the same type as the identifier.
Example var x: integer;
In an algorithm, we can have the instruction
x: = 10; the variable x then contains 10 fco
x: = x + 40; co the variable x then contains 50 fco
e) Reading
The read instruction is used to modify the contents of a variable, the syntax is as
follows:
read (identifier);
The read instruction causes the interrupt of the machine waiting for a value to be
24
SEQUENCING, OPERATORS AND BASIC INSTRUCTIONS
supplied to it. The user then strikes a keyboard value that is assigned to the
variable designated by identifier. The value must be of the same type as the
receiving variable.
As for the display, we can factorize the reading instructions.
Thus, the writing is as follows: read (ident1, ident2, ..., identn); which
expresses "to read (ident1); read (ident2); ... read (identn);"
Note
We note in this example that to calculate the volume we use the result of the
previous calculation (that of the surface) to minimize the number of operations.
1 Algorithm computation;
2 x, y, z: integer;
3 begin
4 x:=5;
5 y:=10;
6 z:=2*x-y;
25
SEQUENCING, OPERATORS AND BASIC INSTRUCTIONS
7 z:=y-6;
8 y:=x+z+6;
9 x:=6*y;
10 write (x);
11 y:=y-1;
12 write (y,z);
13 end
14
26
SEQUENCING, OPERATORS AND BASIC INSTRUCTIONS
year into a date that expresses the number of the day in the month. For example
32/2007 corresponds to 01/02/2007
Exercise 18: Number between two days
Propose an algorithm to calculate the number of days between two given dates in
the form dd / mm / yyyy. It is assumed that both dates belong to the same year.
Exercise 19: Date of the following day
Propose an algorithm that reads a date in the form dd / mm / yyyy and determines
the date of the next day.
Exercise 20: System of equations
Write an algorithm that solves a linear system of two equations with two unknowns
parameters.
Exercise 21: Magic square
A magic square is a matrix of order n whose elements are all integers between 1
and n2 such that the sum of the elements of each column and the sum of the
elements of each diagonal line are equal. Propose an algorithm that builds a magic
square of order n.
Exercise 22:Verification of a permutation
Write an algorithm that reads an integer n then a permutation of n elements and
verifies that the values entered constitute a permutation of 1, ..., n.
Exercise 23:
Write an algorithm that reads 2 square matrices of order n, posters, calculates their
product and displays.
Exercise 24:Scalar product of two vectors
Let U and V be two vectors of real n and of components u 1, u2, ..., un and v1, v2 ...,
vn respectively. Calculate the U * V scalar product.
27
CONTROL
V-
V
STRUCTURES
A. Conditional structure
29
CONTROL STRUCTURES
Example
Write an algorithm that displays the result in the exam of a student whose grade is
being read in data. It is admitted if its mark is greater than or equal to 10,
postponed if its mark is <8 and admitted orally if its mark is between 8 and 10.
1 Algorithm dysplay_result;
2 var mark:real;
3 begin
4 write("Type the name of the student");
5 read(mark);
6 if(mark>=10)then write("Admitted");
7 else
8 if(mark<8)then write("postponed");
9 else write("Admitted for oral");
10 endif
11 endif
12 end
B. Repetitive structure
Introduction
In many problems, one is required to perform several actions several times.
Example: the calculation of the payroll of employees of a company, the edition of
the transcripts of the students of a faculty, the edition of the invoices of the
customers, ...
If the number of repetitions is large, it is tedious to rewrite the same algorithm n
times, this is impossible in some cases, even in the majority of cases. It is therefore
wrong to be able to express the repetition of an action or an iteration that once
initialized continues until an event occurs: it is the event of stop of the iteration.
Example
A program segment repeatedly asks for entry of a number in the range 1 to 100
until a valid number is entered.
30
CONTROL STRUCTURES
1 REPEAT
2 write(“Enter a number between 1 and 100”);
3 read(number);
4 UNTIL (number < 1 OR number > 100 )
1 Algoritm sport_survey;
2 Var letter: char;
3 athletics,swimming,football, badminton: integer;
4 BEGIN
5 REPEAT
6 write(“Type in the letter chosen or Q to finish”);
7 write(“A: Athletics”);
8 write(“S: Swimming”);
9 write(“F: Football”);
10 write(“B: Badminton”);
11 write(“Enter data”);
12 read(letter);
13 If (letter = ‘A') then athletics = athletics + 1;
14 If (letter = ‘S') then swimming = swimming + 1;
15 If (letter = ‘F') then football = football + 1;
16 If (letter = ‘B') then badminton = badminton + 1;
17 UNTIL (letter = ‘Q')
18 write(“Athletics scored”, athletics, “votes”);
19 write(“Swimming scored”, swimming, “votes”);
20 write(“Football scored”, football, “votes”);
21 write(“Badminton scored”, badminton, “votes”);
22 END
Example
A program segment to print out each character typed at a keyboard until the
character ‘q' is entered.
Write a program that will output the square root of any number input until the
number input is zero.
In some cases, a variable has to be initialized before execution of the loop as shown
in the following example.
31
CONTROL STRUCTURES
1 Algorithm square_root;
2 Var number :real;
3 BEGIN
4 write(“Type in a number or zero to stop”);
5 read(number);
6 WHILE number <> 0
7 Square = number * number
8 write(“The square of the number is”, square);
9 write(“Type in a number or zero to stop”);
10 write(number);
11 ENDWHILE
12 END
Example
1 FOR (n = 1, n <= 4, n + 1)
2 write(“loop”, n);
3 ENDFOR
1 Algorithm average;
2 Var n, count :integer;
3 Sum, number, average :real;
4 BEGIN
5 write(“How many numbers do you want to input”);
6 read(count);
7 Sum = 0;
8 FOR (n = 1, n <= count, n + 1)
9 write(“Input the number from your list”);
10 read(number);
11 Sum= sum + number;
12 ENDFOR
13 Average = sum / count;
32
CONTROL STRUCTURES
Design an algorithm and the corresponding flowchart for finding the sum of n
numbers.
1 Algorithm integer_sum;
2 Var n, sum:integer;
3 Begin
4 sum = 0;
5 write(“Input value n”);
6 read(n);
7 For i from 1 to n do
8 write("Input a value");
9 read(value);
10 sum = sum + value
11 ENDFOR
12 write(sum);
13 End
In this example, we have used I to allow us to count the numbers, which we get for
the addition. We compare I with n to check whether we have exhausted the
numbers or not in order to stop the computation of the sum (or to stop the iteration
structure). In such a case, i is referred to as a counter.
C. Exercises
Exercises
1. Design an algorithm and the corresponding flowchart for finding the sum of
the numbers 2, 4, 6, 8, ..., n
2. Using flowcharts, write an algorithm to read 100 numbers and then display
the sum.
3. Write an algorithm to read two numbers then display the largest.
4. Write an algorithm to read two numbers then display the smallest
5. Write an algorithm to read three numbers then display the largest.
6. Write an algorithm to read 100 numbers then display the largest.
7. Write an algorithm to display the sum of the 100 numbers read in data. The
algorithm will also display their average.
8. Write an algorithm that displays the L character followed by the E character
(LE) in a sentence that ends with the symbol"."
9. Write an algorithm that calculate an were a and n are read from the
33
CONTROL STRUCTURES
keyboard.
10. Write an algorithm which read a value n as input compute Un=Un-1+Un-2
whith U0=U1=1
11. Write an algorithm to determine the greatest common divisor (GCD)of two
numbers read as input
12. Write an algorithm that determines and displays the number of words
contained in a sentence completed by the dot marker ".". To put it simply,
we will consider that the separator character of the words is ' ' (the blank
space) there are no other separators.
13. Let s be a sequence of positive integers ordered in ascending order and
terminated by the -1 marker. Write an algorithm to determine the length L
of the longest sub-sequence extracted from s and having only identical
elements. e.g if the following is s = 11227779-1, L = 3.
14. Write an algorithm that prints the successive terms of the general term
sequence 1/(2 * n). Suppose that n> 0. The printing is made until a term
is less than 0.0001
15. Write an algorithm that calculates the series 1-1/3+1/5-1/7+...+(-1)n/
(2*n+1) with a precision whose value will be read in data.
16. Write an algorithm that calculates an approximate value of sin (x), with x in
rad. The algorithm will use the x-x3/3!+x5/5!-x7/7!+...+(-1)nx2n+1/(2n!)
development for evaluating sin (x)
34
Array
VI-
VI
Introduction
When a program manipulates many variables that contain “similar” forms of data,
organizational problems quickly arise. Here is an example: In an ice-skaking
competition, each skater's performance is judged by six judges, who assign
fractional scores. The six scores must be collected and manipulated in various
ways, e.g., printed from highest to lowest, averaged, multiplied by weighting
factors, and so on. Say that the six scores are saved in these variables,
An array is the most basic data structure to visualise
Most, if not all, computer languages provide it as a builtin
Definition An array is a collection of elements stored in contiguous memory
locations providing random access to its elements
- The elements are ordered according to an index set, which is a set of
integers
Random access – accessing any element takes the same time
Indexing could be either 0-based or 1-based
Applications of arrays
Despite its simplicity, an Array has wide range of applications
Best data structure for in memory storage of infrequently changing data
Many sorting applications use arrays explicitly or as auxiliary data structures
For implementing other and more complicated data structures
... such as Stack, Queue, List, and Search Tree
35
Array
variation interval.
Note : Observation
It is also possible to use the following syntax to declare an array.
var : array of T;
where
is the name of the variable declare as array type.
inf and sup are constant identifiers which represent the left and the right
boundary of the array with .
Example
Write an algorithm which allow to read 100 integers, then displays the list of those
integers in the reverse reading order.
1 Algorithm ReverseIntegerList;
2 type intvect:array[1 ..100]of integer;
3 var Arr:intvect;
4 i:integer;
36
Array
5 Begin
6 write("Type in a list of 100 integer");
7 i:=1;
8 Repeat
9 write("Type in the integer number", i);
10 read(Arr[i]);
11 i++;
12 Until(i==101)
13 write(" The reverse array is:");
14 i:=100;
15 while(i>0)do
16 write(Arr[i]);
17 i:=i-1;
18 endwhile
19
20 End
1 Algorithm number_of_a;
2 const N:=100;
3 type charvect: array[1 ... N]of char;
4 var A: charvect;
5 count, i :integer;
6 Begin
7 write("Type in a string");
8 i:=1;
9 read(A[i]);
10 while((A[i]<>0)&&(i<=100)) do
11 i+=1;
12 read(A[i]);
13 endwhile
14 if(A[i]=='.')then
15 begin
16 count:=0;
17 j:=1;
18 while(A[j<>0]) do
19 if(A[j]=='a') then count++;
20 endif
21 j+=1;
22 endwhile
23 write("The number of a is:", count);
24 end
25 else write("Typping error");
26 endif
27 End
B. Multidimensional array
37
Array
Example
type = array of integer;
var : ;
To have access to an element of the array, we need to know the line and column
indexes of which that element belongs.
38
Array
Note
represent the element at the position , i.e st the line and column of
the array .
1 2 3 4 5 6 7 8 9
6
Table 5 Illustration of a two dimensional array
n dimensional array
We can generalize the definition of the one dimensional array to n dimension
following the syntax below:
type of T;
Note:
C. Tutorial set 3
39
Array
Exercise 5: Check
Write an algorithm which displays TRUE if a number nb is equal to the sum of two
consecutive elements of an array A and false otherwise. The number nb and the
array A are read in data.
Exercise 6:
Given two dimensional array(NxN).
write an algorithm that recognize if the array is magic or not.
An array is magic if the sum of the diagonal of N lines and N column are all equals.
40
Searching and
VII-
VII
Sorting
A. Searching
b) sequential search.
The most naive way is to compare the element sought x successively to all the
elements of the list L according to the following sequential diagram:
The indexes of L are between 1 and the length of the list L
To compare x and the ith element of the list L, one will be interested at first
in the search for any solution, one stops the progression in the list as soon
as one finds an element equal to x.
In the case where the list is represented by an array A, A [i] designates the i th
element of the list and the following algorithm will tell us if the element x is in the
Array A.
1 Algorithm sequentialSearch;
2 CONST N=100;
3 VAR A: array[1...N] of element;
4 x: element;
5 i: integer;
6 BEGIN
7 write("Type in the array''s elements");
8 for i from 1 to N do
9 write("Type in the",i,"th element");
10 read(A[i]);
11 endfor
12 write("Type in the element to search");
13 read(x);
14 i:=1;
15 while((i<=N)&&(A[i]!=x))do
16 i++;
41
Searching and Sorting
17 endwhile
18 if(i==N+1) then write("Element not found");
19 else write("Element found at position",i);
20 endif
21 END
In this algorithm, the condition of the while loop is double, after each iteration, a
test of the the end of the end of the list is done ( ), equally, the comparison
between x and the element at position is done.
1 Algorithm sequentialSearch;
2 CONST N=100;
3 CONST M=101;
4 VAR A: array[1...M] of element;
5 x: element;
6 i: integer;
7 BEGIN
8 write("Type in the array''s elements");
9 for i from 1 to N do
10 write("Type in the",i,"th element");
11 read(A[i]);
12 endfor
13 write("Type in the element to search");
14 read(x);
15 i:=1;
16 A[M]='x';
17 while(A[i]!=x)do // a single condition
18 i++;
19 endwhile
20 if(i==M) then write("Element not found");
21 else write("Element found at position",i);
22 endif
23 END
42
Searching and Sorting
43
Searching and Sorting
1 Algorithm BinarySearch;
2 CONST N=100;
3 VAR A: array[1...N] of element;
4 x: element;
5 i, m, g,d, res: integer;
6 BEGIN
7 write("Type ine the array's elements");
8 for i from 1 to N do
9 write("Type in the",i,"th element");
10 read("A[i]");
11 endfor
12 co The array is supposed to be sort fco
13 write("Type in the element to be sorted");
14 read(x);
15 g:=1;
16 d:=N;
17 rest:=-1;
18 while((g<=d)&&(rest==-1)) do
19 m:=(g+d)div2;
20 if(x==A[m]) then res:= m
21 else
22 if (x<A[m]) then d:=m-1;
23 else g:=m-1;
24 endif
25 endif
26 endwhile
27 if (re==-1) then write("element not found");
28 else write("element found at position:", res);
29 END
d) auto-adaptive search
This search method aims to reorganize the list of elements
B. Sorting
44
Searching and Sorting
- Iterative
- Recursive
- Divide-and-conquer
- Best/worst/average-case bounds
- Randomized algorithms
Applications of Sorting
Uniqueness testing
Deleting duplicates
Prioritizing events
Frequency counting
Reconstructing the original order
Set intersection/union
Finding a target pair x, y such that x+y = z
Efficient searching
Selection Sort
We can also find the smallest and put it the front instead
45
Searching and Sorting
Bubble Sort
46
Searching and Sorting
47
Searching and Sorting
Insertion Sort
48
Searching and Sorting
C. Exercise
Exercise
Write an algorithm which read an array of 50 students names of Beng1. The
algorithm read also an array of 50 real numbers representing the Algorithm Basics
CA marks of those students. The name an students marks are read simultaneously.
The algorithm will sort the array of marks in descending order and process the
ranking in order of merit( from the highest mark to the lowest). The result should
be display as follow:
49
Procedures and
VIII-
VIII
Functions
Introduction
When programs grow larger than the small examples presented so far, it becomes
necessary to introduce some structure that makes them easier to read and to
maintain. Usually, this is done by dividing the tasks that have to be executed into
subtasks which may again be subdivided, and indicating the order in which these
subtasks have to be executed and which are their activation conditions. To facilitate
this structured approach, Mosel provides the concept of subroutines. Using
subroutines, longer and more complex programs can be broken down into smaller
subtasks that are easier to understand and to work with. Subroutines may be
employed in the form of procedures or functions. Procedures are called as a
program statement, they have no return value, functions must be called in an
expression that uses their return value.
Mosel provides a set of predefined subroutines (for a comprehensive documentation
the reader is referred to the Mosel Reference Manual), and it is possible to define
new functions and procedures according to the needs of a specific program. A
procedure that has occured repeatedly in this document is writeln. Typical examples
of functions are mathematical functions like abs, floor, ln, sin etc.
Procedures
A procedure is a separate piece of the program that is named and can be executed
by calling it from other parts of the program. The procedure can be given values for
it to
work with. These values are given names in the procedure code, sometimes
referred to as formal parameter names.
Function
Functions are very similar to procedures except that the function call will also return
a value to the place where the function was called.
51
PROCEDURE AND
IX-
IX
FUNCTIONS
INTRODUCTION
When programs grow larger than the small examples presented so far, it becomes
necessary to introduce some structure that makes them easier to read and to
maintain. Usually, this is done by dividing the tasks that have to be executed into
subtasks which may again be subdivided, and indicating the order in which these
subtasks have to be executed and which are their activation conditions. To facilitate
this structured approach, Mosel provides the concept of subroutines. Using
subroutines, longer and more complex programs can be broken down into smaller
subtasks that are easier to understand and to work with. Subroutines may be
employed in the form of procedures or functions. Procedures are called as a
program statement, they have no return value, functions must be called in an
expression that uses their return value.
Mosel provides a set of predefined subroutines , and it is possible to define new
functions and procedures according to the needs of a specific program. A procedure
that has occured repeatedly in this document is writeln. Typical examples of
functions are mathematical functions like abs, floor, ln, sin etc.
53
PROCEDURE AND FUNCTIONS
54
PROCEDURE AND FUNCTIONS
Parameters
Parameters allow us to pass information or instructions into functions and
procedures. They are useful for numerical information such as stating the size of
an object.
Parameters are the names of the information that we want to use in a function or
procedure. The values passed in are called arguments.
For instance, we can create a procedure that draws a square - but for it to be useful
we need to also be able to specify how large it should be.
The following example creates a procedure called 'square'. In the line where we
define the name for this procedure, we have included a variable called 'distance'
inside the brackets. Distance is a parameter - it allows us to pass a value into the
procedure for it to use.
55
PROCEDURE AND FUNCTIONS
Where list of parameters is the set of parameters associated with specific types and
the form (var v1: type1, var v2: type2, var v3: type3, ..., var vn: typen).
Example (var c: character) (var count: integer, var res: real).
It is also possible to factorize (var count, i: integer)
During the definition of the subroutines the parameters are called formal
parameter, on the other hand when the call to a subroutine if this one has
parameters they will be called effective parameters.
1 procedure square;
2 var nb,c:entier;
3 begin
4 write("Type in a number");
5 read(nb);
6 c:=nb*nb;
7 write("The square is:", c);
8 end
c) A procedure which reads three integers and return the highest using
section b)
1 procedure highest();
2 var nb1, nb2, nb3, hg: integer;
3 Begin
4 write("Type in three integers");
5 read(nb1);
6 read(nb2);
7 read(nb3);
8 hg:=highestInt(nb1, nb2, nb3);
9 write("The highest is:", hg);
10 End
56
PROCEDURE AND FUNCTIONS
Extra : Recursion
Recursion means calling a function in itself. If a function invokes itself, then the
phenomenon is referred to as recursion. However, in order to generate an answer,
a terminating condition is must. In order to understand the concept, let us take an
example. If the factorial of a number is to be calculated using the function defined
as follows:
and , and if the value of is , then the process of calculating can be explained with
the help of the figure below is calculated and its value is used to calculate , which
in turn is used for calculating . helps to calculate and finally, is used to calculate .
As is evident from the above figure,, recursion uses the principle of last in first out
and hence requires a stack. One can also see that had there been no , the
evaluation would not have been possible. This was the reason for stating that
recursion requires a terminating condition also.
57
Section
X-
59