0% found this document useful (0 votes)
10 views47 pages

ADS - II Course Chapter - 2 Modularity (Func Proc)

The document discusses subprograms, specifically functions and procedures, within the context of algorithms and data structures. It covers modularity, parameter passing, local and global variables, and the structure and syntax of functions. The content is aimed at helping students understand how to design and implement modular code effectively.

Uploaded by

hyourinkang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views47 pages

ADS - II Course Chapter - 2 Modularity (Func Proc)

The document discusses subprograms, specifically functions and procedures, within the context of algorithms and data structures. It covers modularity, parameter passing, local and global variables, and the structure and syntax of functions. The content is aimed at helping students understand how to design and implement modular code effectively.

Uploaded by

hyourinkang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Ministry of Higher Education and Scientific Research

Djilali BOUNAAMA University - Khemis Miliana(UDBKM)


Faculty of Science and Technology
Department of Mathematics and Computer Science

Chapter 2

Subprograms:
Functions and Procedures
MI-L1-UEF121 : Algorithms and Data Structures II

Noureddine AZZOUZA

1
Course
Topics
1. Modularity

2. Passing parameters

3. Local variables and global variables

4. Functions

5. Procedures

2
ASD II Noureddine AZZOUZA
Modularity

3
Introduction Algorithm Calcul_Combinaison ;
Var n,p,c : integer ;
fact_n, fact_p, fact_np: integer;
Problem Begin
//les entrées
Read (n,p);

Combination Calculation //manipulation des données


fact_n = 1;
For i := 1 to n Do
fact_n := fact_n * i;
Modularity

fact_p = 1;
For i := 1 à p Do
fact_p := fact_p * i;

fact_np = 1;
For i := 1 à (n-p) Do
fact_np := fact_np * i;

c := fact_n/(fact_p*fact_np);

//les sorties
Write (‘le nombre de combinaisons=‘,c);
End.
4
ASD II Noureddine AZZOUZA
Introduction

Problem
fact_n = 1;
Repeating For i := 1 to n Do How to
fact_n := fact_n * i;
the write the
factorial fact_p = 1; solution
For i := 1 to p Do
calculation only once?
Modularity

fact_p := fact_p * i;
Organize
fact_np = 1;
For i := 1 to n-p Do the code?
fact_np := fact_np * i;

Modules / Subprograms
5
ASD II Noureddine AZZOUZA
Subprograms

Definition
 A subprogram or module is a set of instructions with a well-defined
interface that performs a specific task.

 The purpose of a subroutine is:


Modularity

1. Receive input data


2. Carry out processing/transformation of this data
3. Return one or more results

 The interface consists of the inputs/outputs of the module. It makes it


possible to establish the link between the module and its environment
(main algorithm, other modules).

6
ASD II Noureddine AZZOUZA
Subprograms

Structure
Interface Results
Data (inputs)
(outputs)
Type that depends
on the output

Type of Subprograms
Modularity

0 to n inputs name_sub_programs 0 to n
outputs

Role of Sub-Program
unique and meaningful Role that indicates what
name that is used in the exactly the subroutine
declaration and appeal does
7
ASD II Noureddine AZZOUZA
Subprograms

Types
 Depending on the number and type of outputs, there are two (02) types
of Subprograms (modules):

1. Function : When the module returns a single (1) result and this
result is elementary (basic) type data, example:
Modularity

 Function that calculates the sum of an array of integers (return an integer)

 Function that checks if a number is prime (return a boolean)

2. Procedure : When the module returns 0 to n results or the result is


of structured type, examples:
 Procedure that displays a matrix (return 0 result)

 Procedure solves a 2nd degree equation (return 2 results)

 Procedure that reverses the content of an array(return an array)


8
ASD II Noureddine AZZOUZA
Subprograms

Qualities
 In order to decide whether a sequence of instructions deserves to be
designed in the form of a subroutine or module, the following qualities
must be checked:
Modularity

1. Reuse: a module is designed so that it can be reused in several


solutions. It must be generalized as much as possible.

2. Independence: avoid using global variables in a module so that it is


independent of the main algorithm. Same thing for reads and writes.

3. Simplicity: keep your code readable and design a module that meets a
specific task.

9
ASD II Noureddine AZZOUZA
Modular Approach

Definitions
 Modularity: “It is a way of thinking aimed at building algorithms starting
from a very general level and gradually detailing each treatment, until
arriving at the lowest level of description.”

 Modularity: is a Top-down Analysis which divides (cuts) a problem


Modularity

into sub-problems to conquer them then combine the sub-solutions


and obtain an overall result.

 Modularity: the basis of structured programming consists of solving a


problem by building simple, readable and reusable modules.

10
ASD II Noureddine AZZOUZA
Modular Approach

Objectifs / Goals
 Cut (divide) a complex problem into simple sub-problems which will be
solved separately.
 Propose a solution to a (sub)problem once and only once

Divide conquer & combine


Modularity

Sous

Sous
P11

S11
Prb

Sol
Sous

Sous
Prb
Problème complexe P

Sol
P1

S1
Sous

Sous
P12

S12

Solution finale S
Prb

Sol
Sous

Sous
Prb

Sol
P2

S2
Sous Sous

Sous Sous
P31

S31
Prb

Sol
Sous

Sous
Prb

P32

S32

Sol
Prb
P3

S3
Sol
Sous

Sous
P32

S32
Prb

Sol
11
ASD II Noureddine AZZOUZA
Modular Approach

Modular Approach Stages

2nd STEP: Analysis


and Design
Modularity

1st STEP:
• Modular Cutting/Split 3rd STEP:
Understanding
• Construction of Realization
the problem Modules

12
ASD II Noureddine AZZOUZA
Modular Approach

Modular Breaking/Splitting
 Break the problem into coherent modules:

 Start extracting obvious modules that are easy to detect.


Modularity

 Improve and enrich the breakdown as you progress in solving the


problem

13
ASD II Noureddine AZZOUZA
Modular Approach

Build Modules
 To build a module, we start with its description:

 Draw the Module


 Give it a name
Modularity

 Define your interface


 Specify its nature (function or procedure)
 Indicate its role

 If the module already exists, we do not build it. Its description is


given only
14
ASD II Noureddine AZZOUZA
Modularité

Avantages / Benefits
 Cutting into coherent modules is done using a Top-Down Approach

 Simplifies design

 Independent and separate construction of modules


Modularity

 Readability and ease of understanding of algorithms

 Ease of maintenance and code updating

 Reuse of modules (Subprograms) already designed

15
ASD II Noureddine AZZOUZA
Communication & Calls

Communication between Modules


Algorithm exercice;
Var –
Module_A(parm1, parm2, ...,parmn)
Communication


Modules Module_A
Begin
-
-
Call Module_A(arg1, arg2, ..., argn); Called Module
-
-
End.
Calling module

 When a call to a module is encountered,


 Suspend the execution of the calling module (For example: Main algorithm)
 Start and run the called module (For example: Module_A)
16  Resume execution of the calling module
ASD II
just after the calling instruction Noureddine AZZOUZA
Communication & Calls

Parameters and Arguments


 The variables used during the construction of the module (subroutine header) are
called Parameters or formal parameters
Communication

 Example : les paramètres (ou paramètre formels) du module « Module_A » sont :


parm1, parm2, ...,parmn

 The variables used when calling (using) a module are called Effective parameters or
arguments. They replace the formal parameters during the call.
 Example : les arguments (ou paramètre effectifs) du module « Module_A » utilisés
dans son appel à l’algorithme principale sont : arg1, arg2, ..., argn

 The number of arguments must match the number of parameters.


 The order of arguments must match the order of parameters.
 The type of the kth argument must match the type of the kth parameter.
17
ASD IIand parameters is done using the order.Noureddine AZZOUZA
 The correspondence between arguments
Passing Parameters

Parameters Passing Modes


Params Passing Modes

 It is the substitution of formal parameters by an effective parameters when calling a


subprogram.
 On distingue deux mode de passage :
 Passing by Value: Any modification of the content of the parameter in the called program has
no effect on the value of the effective parameter in the calling program.

 Passing by Variable (by Reference): any modification of the content of the formal parameter
automatically results in the modification of the effective parameter.

 formal parameters passed by variable are preceded by the keyword VAR in the header of
the

type_module nom_fonction (Formal input parameters; VAR Formal output parameters);;

18
ASD II Noureddine AZZOUZA
Passing Parameters

Passing by Value
Params Passing Modes

 Copy the argument values to the start of the subprogram.


 This is in fact an assignment of the values of the arguments in the associated formal parameters.
 Can receive any expression (constant, variable, expression, function call, etc.)
 Peut recevoir n’importe qu’elle expression (constant, variable, expression, appel de fonct ...)
 Example subroutine (function) which surf := Surface (x, y); Call
calculate the area of a rectangle.
equivalent to

:
Function Surface(long, larg:real) real; :
Function Surface(long, larg:real) real;
Var S: integer; Var S: integer;
Module Begin Begin
S := long * larg; long := x; larg := y;
Surface := S; S := long * larg;
End; Surface := S;
19 End;
ASD II Noureddine AZZOUZA
Passing Parameters

Passing by Variable
Params Passing Modes

 In passing by variable (or reference) the parameter itself becomes the argument,
 that is, the parameter becomes an alias of the argument.
 Can only be linked to variables..
 Example : subroutine (procedure) which swaps (exchanges) the values of two variables..
Echange (a, b); Call

équivalent à

Procedure Echange(VAR x, y:integer); Procedure Echange(VAR x, y: integer);


Var z: integer; Var z: integer;
Module Begin Begin
z := x; z := a;
x := y; a := b;
y := z; b := z;
20
End; End;
ASD II Noureddine AZZOUZA
Passing Parameters

Params Passing Modes


Params Passing Modes

 Passing by Value: is adopted when we want the module to return the same value that the
parameter had at the input, or the parameter is not used in other modules (useless to
find the final result).

 Passage by Variable (by Reference): is adopted when the input parameter is modified
during the execution of a subroutine and it is the modified content of the parameter that
we want.

Will the formal parameter be modified by the called program?


YES NO

Would this parameter, after its modification, be used by


another subroutine or by the main program?
Passing by Value
YES NO

21
Passage by Variable Passing by Value
ASD II Noureddine AZZOUZA
Passing Parameters

Notes
Params Passing Modes

 It is recommended to use:

 A passing by values for the input parameters of a function.

 A passing per variable for all the output parameters of a procedure.

22
ASD II Noureddine AZZOUZA
Local and Global

Local Variables and Global Variables


There are two categories of variables:
Local and Global

 Local Variables: which are defined in a module and which can only
be manipulated in this module.

 Global Variables: which are defined in a calling module and can be


manipulated in this module and in all modules called by this
module.

 The scope: of a variable is the set of modules where this variable is


23
accessible (or defined).
ASD II Noureddine AZZOUZA
Local and Global

Local Variables and Global Variables


Module_Appelant
Variable Scope (Portée)
Local and Global

Var A, B, X: real;
Module_1 Module_Appelant , Module_1,
A,B
Var X: integer; Module_2, Module_3
T: booléen; T Module_1, Module_2
Module_2
C Module_2
Var C: integer;
X:déclaré au
Module_Appelant
Module_Appelant
Module_3
Var X, Y, Z: integer; X:déclaré au
Module_1, Module_2
Module_1
Begin X:déclaré au
- Module_3
Module_3
-
End; Y, Z Module_3
24
ASD II Noureddine AZZOUZA
Functions

25
Functions

Definition and Description


 A function is a sub-programme (subroutine or module) which returns a
single result (single output) of simple (elementary) type: integer, real,
boolean, character. It can receive 0 to n input parameters.

FUNCTION
Functions

0 to n inputs Function_name 1 simple objet

Role of the function

Description of a fuonction
26
ASD II Noureddine AZZOUZA
Functions

Structure and Syntax


Header :
Function fonction_name (List of formal input parameters :Type) Return Type;

Type – 𝑫é𝒄𝒍𝒂𝒓𝒂𝒕𝒊𝒐𝒏 𝒅𝒆𝒔


Const – 𝒅𝒐𝒏𝒏é𝒆𝒔 (𝒐𝒃𝒋𝒆𝒕𝒔)
Var – 𝒍𝒐𝒄𝒂𝒍𝒆𝒔
Functions

Body Begin
-
-
- 𝑻𝒓𝒂𝒊𝒕𝒆𝒎𝒆𝒏𝒕𝒔
-
-
- fonction_name := Result;
End;

27
ASD II Noureddine AZZOUZA
Functions

Properties & Notes


 The body of a function can contain all declarations (Type, Const, Var,
etc.) and algorithmic structures (Assignment, Repetition, Conditional,
etc.).

 The calculated result (return value) must be passed in the function


Functions

name. This assignment is located – in most cases – at the end of the


function.

 Formal parameters describe the input parameters used in the function


as well as their type and their passing mode.

 In Functions, formal parameters are used in passing-by-value mode.

28
ASD II Noureddine AZZOUZA
Functions

Calls
 Calling a function can be used as:
 Expression in an assignment,
 Operand in a condition
 Argument in a procedure or function call
Functions

 Examples:
 X := Prime (a)
 if Prime (a) = True then write ( a, ‘is prime’)
 Res := Prime (Fact(n))

29
ASD II Noureddine AZZOUZA
Example: Calcul of Combinaisons

1st Step : Split Modules


Function : Fact FUNCTION

Fact (n) = n! n: integer Fact integer


= n*(n-1)*....*3*2*1
Role : Retour the factoriel of n
(n!)
Functions

Function : Comb FUNCTION


n: integer
Comb (n,p) =
𝑝
𝐶𝑛 =
𝑛! Comb integer
𝑝!∗ 𝑛−𝑝 !
p: integer

Role : return the num of


= Fact(n)/Fact(p)*Fact(n-p)
combinaison of p objets from n

30
ASD II Noureddine AZZOUZA
Example: Calcul of Combinaisons

2nd Step: Construction of modules


:
Function Fact (n: integer) integer; :
Function Comb (n , p: integer) integer;
Var F, i: integer; Functions : Fact;
Begin Begin
F := 1; Comb := Fact(n)/ Fact(p)* Fact(n-p);
for i := 1 to n Do End;
Functions

F := F * i;

Fact := F;
End;

31
ASD II Noureddine AZZOUZA
Example: Calcul of Combinaisons

3rd Step: Main Algorithm


Algorithm Calcul_comb;
Var x,y,c: integer;
Functions : Comb;
Begin
Read(x,y);
Functions

c := Comb(x,y);
Write (‘Le nombre de combinaison = ‘, c);
End;

32
ASD II Noureddine AZZOUZA
Function declaration

PASCAL C
FUNCTION nom_fonction (Input parameters): type_retour; type_retour nom_fonction (Input parameters);
Programmation C / PASCAL

var 𝐷é𝑐𝑙𝑎𝑟𝑎𝑡𝑖𝑜𝑛 𝑑𝑒𝑠 𝑑𝑜𝑛𝑛é𝑒𝑠 𝑙𝑜𝑐𝑎𝑙𝑒𝑠 { 𝐷é𝑐𝑙𝑎𝑟𝑎𝑡𝑖𝑜𝑛 𝑑𝑒𝑠 𝑑𝑜𝑛𝑛é𝑒𝑠 𝑙𝑜𝑐𝑎𝑙𝑒𝑠


begin -
- - 𝐼𝑛𝑠𝑡𝑟𝑢𝑐𝑡𝑖𝑜𝑛𝑠
𝐼𝑛𝑠𝑡𝑟𝑢𝑐𝑡𝑖𝑜𝑛𝑠
- -
- -
nom_fonction := valeur_retour; return valeur_retour;
fin; }

33
ASD II Noureddine AZZOUZA
Function declaration

PASCAL
Programmation C / PASCAL

 In PASCAL, Functions and procedures must


be declared before the main program.

 In general, each called module must be


constructed before the calling module for it
to be recognized.

 In this example:
 A Call to a Fact function (line 17)
 n: parameter (formal parameter) (line 5)
 x: argument (effective parameter)(line 17)

34
ASD II Noureddine AZZOUZA
Function declaration

C
Programmation C / PASCAL

 In C language, Functions and procedures can


be declared before and after the main
function.

 If the function is placed before the main ,


the compiler checks the parameters and
executes the function.

 If the function is placed after the main , we


need to define a prototype of the function
for it to be recognized.

35
ASD II Noureddine AZZOUZA
Function declaration

C
Programmation C / PASCAL

 A prototype is a function declaration so that


it can be used (called) even before it is coded.

 The prototype is placed at the beginning of


the program (just after the libraries
declaration).

 A prototype is declared as a function

type_retour nom_fonction (Input parameters);

36
ASD II Noureddine AZZOUZA
Procedures

37
Procedures

Definition and Description


 A procedure is a sous-programme (subroutine or module) which returns
0 to n results (multiple output) of simple or compound type. It can
receive 0 to n input parameters.
Procedures

PROCEDURE

0 to n inputs Procedure_name 0 to n outputs

Role of the procédure

Description of a procedure
38
ASD II Noureddine AZZOUZA
Procedures

Structure & Syntax


Header Procedure procedure_name (List of formels input and output parameters :Type) ;
Type – 𝑫é𝒄𝒍𝒂𝒓𝒂𝒕𝒊𝒐𝒏 𝒅𝒆𝒔
Const – 𝒅𝒐𝒏𝒏é𝒆𝒔 (𝒐𝒃𝒋𝒆𝒕𝒔)
Procedures

Var – 𝒍𝒐𝒄𝒂𝒍𝒆𝒔

Body Begin
-
- 𝑻𝒓𝒂𝒊𝒕𝒆𝒎𝒆𝒏𝒕𝒔
-
-
-
End;

39
ASD II Noureddine AZZOUZA
Procedures

Properties & Notes


 The body of a procedure can contain all declarations (Type, Const, Var,
etc.) and algorithmic structures (Assignment, Repetition, Conditional,
etc.).
Procedures

 The formal parameters describe the input and output parameters


used in the procedure as well as their type and their passing mode.

 In Procedures, formal output parameters must always be described in a


passing-by-variable mode.

40
ASD II Noureddine AZZOUZA
Procedures

Calls
 Calling a procedure is a primitive action. It is composed
of the name of the procedure followed in parentheses by the list of effec
tive input and output parameters separated by commas.
Procedures

 As for functions, the number, order, and type of the effective paramete
rs must be identical to those of the formal parameters.

 Examples:
 remplir_tab (n, T)
 echange (x, y)

41
ASD II Noureddine AZZOUZA
Example: Convert a time T (in seconds) to hours, minutes and seconds

1st Step : Split Modules

Procedure: convert_temps PROCEDURE

convert_temps (T, h, m, s)
h : integer
1. On divise T sur 360 : le quotient est h T: integer convert_temps m : integer
Functions

s : integer
2. Le reste de cette division est divisé sur 60
a. Le quotient est m Role : Converts a time T (in seconds) into
b. Le reste est s h hours, m minutes and s seconds

42
ASD II Noureddine AZZOUZA
Example: Convert a time T (in seconds) to hours, minutes and seconds

2nd Step: Construction of modules


Procedure convert_temps (T: integer; VAR h, m, s : integer);
Var R: integer;
Begin
h := T DIV 3600;
Functions

R := T MOD 3600;
m := R DIV 60;
s := R MOD 60;
End;

43
ASD II Noureddine AZZOUZA
Example: Convert a time T (in seconds) to hours, minutes and seconds

3rd Step: Main Algorithm


Algorithm Convert;
Var A, x, y, z: integer;
Procedures : convert_temps;
Begin
Read(A);
Functions

convert_temps(A, x, y, z);
Write (A,'=',x,'heures et ',y,' minutes et ',z,'secondes');
End;

44
ASD II Noureddine AZZOUZA
Exemple: Convertir un temps T (en secondes) en heures, minutes et secondes

PASCAL C
PROCEDURE nom_procedure (Input/output parameters); void nom_fonction (Input/output parameters);
Programmation C / PASCAL

var 𝐷é𝑐𝑙𝑎𝑟𝑎𝑡𝑖𝑜𝑛 𝑑𝑒𝑠 𝑑𝑜𝑛𝑛é𝑒𝑠 𝑙𝑜𝑐𝑎𝑙𝑒𝑠 { 𝐷é𝑐𝑙𝑎𝑟𝑎𝑡𝑖𝑜𝑛 𝑑𝑒𝑠 𝑑𝑜𝑛𝑛é𝑒𝑠 𝑙𝑜𝑐𝑎𝑙𝑒𝑠


begin -
- - 𝐼𝑛𝑠𝑡𝑟𝑢𝑐𝑡𝑖𝑜𝑛𝑠
- 𝐼𝑛𝑠𝑡𝑟𝑢𝑐𝑡𝑖𝑜𝑛𝑠
-
- -
- -
fin; }

45
ASD II Noureddine AZZOUZA
Declaration of a Procedure

PASCAL
Programmation C / PASCAL

 Dans cet exemple:


 Un Appel d’une procédure
convert_temps (ligne 5)
 T : paramètre (paramètre formel
d’entrée) (ligne 5)
 h,m,s : paramètre (paramètre formel
de sortie) (ligne 5)
 A : argument (paramètre effectif)
d’entrée (ligne 17)
 x,y,z : argument (paramètre effectif)
de sortie (ligne 17)
46
ASD II Noureddine AZZOUZA
Declaration of a Procedure

C
Programmation C / PASCAL

 In C language, the return type of procedures is


specified as void.

 When declaring the procedure, formal output


parameters are preceded by *.

 When calling this procedure, the effective


output parameters are preceded by &.

47
ASD II Noureddine AZZOUZA

You might also like