0% found this document useful (0 votes)
4 views

Chapitre 4 (Introduction to Algorithmics)

Uploaded by

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

Chapitre 4 (Introduction to Algorithmics)

Uploaded by

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

1st Preparatory Classe

Module: Computer science (Informatique 1)

CHAPTER 4
INTRODUCTION TO ALGORITHMICS

1
INTRODUCTION TO ALGORITHMICS

CHAPTER OUTLINE

I. Fundamentals and Basic Concepts III. Arrays


1. Introduction. 1. One-Dimensional Array (Vector)
2. Foundation of an Algorithmic Language
2. Two-Dimensional Array (Matrix)
a. Basic Structure
b. Variables and Constants 3. N-Dimensional Arrays
c. Variable Types
IV. Functions and Procedures
d. Identifiers and Keywords
e. Instructions 1. Functions
f. Comments a. Function Declaration
g. Expressions b. Function Usage
II. Control Structures c. Local Variables and Global Variables
1. Conditional or Alternative Statement d. Formal Parameters and Actual
2. The 'While' Repetition Loop Parameters
3. The 'For' Repetition Loop e. Function Call
4. The 'Repeat---------Until' Repetition Loop
2. Procedures
5. The conditional test with multiple choices
2
I) FUNDAMENTALS AND BASIC CONCEPTS
1. INTRODUCTION

Algorithmics ?

▪ Algorithmics is the study of algorithms.

An algorithm is a method for solving a given problem in a finite amount of


time

3
I) FUNDAMENTALS AND BASIC CONCEPTS
1. INTRODUCTION

▪ An algorithm is a sequence of logical steps or operations that provides the solution


to a problem.

▪ The program will be the translation of the algorithm into a programming language,

➢ In other words, a language simpler than natural language (pseudo code) in its
syntax, unambiguous, which the machine can use and transform to execute the
actions it can describe.

▪ Pascal, C, Java, and Python are names of programming languages.

LAROUSSE :

An algorithm is a set of operational rules whose sequence enables the


solution of a problem through a finite number of operations
4
I) FUNDAMENTALS AND BASIC CONCEPTS
1. INTRODUCTION

Implementation of a program :
▪ Solving a given problem involves the following sequence of steps:

Language Code

Problem Analyze and resolution Algorithm Codification Program

Compilation
pseudocode

Machine Code

Execution

5
I) FUNDAMENTALS AND BASIC CONCEPTS
1. INTRODUCTION

Implementation of a program :

▪ During the process of writing a program, you can encounter two types of errors:

1. Syntax errors: These errors are noticed during compilation and result from
incorrect syntax in the programming language.

2. Semantic errors: These errors are noticed during execution and result from faulty
analysis. These errors are more serious as they can occur during the program's
runtime operation.

6
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.1 Basic Structure:

▪ The general structure of an algorithm (program) is as follows :

Algorithm Algorithm-Name
Variables:
Declaration of variables and constants
Initialize variables
Declaration of functions
Begin
Read input values (if any)
List of instructions
Display/write output values (if any)
End 7
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.2 Variables and Constants:

▪ A variable is a named memory space of a fixed size, which takes an indefinite number
of different values during the algorithm's execution.

▪ This change of value is done through the assignment operation denoted by (←).

▪ A variable differs from the concept of a constant which, as the name implies, takes
only one unique value during the execution of the algorithm.

▪ Declaration: it allows specifying which variables will be used during the algorithm as
well as the type of value they must respectively take.

8
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.3 Variable Types:

❖ Integers

▪ The integer type characterizes the set of whole numbers.

▪ The possible arithmetic operations on this type are: ‘+’, ‘-‘, ‘*’, ‘/’

▪ These operations, when applied to integer operands, provide an integer result except
for the ‘/’ operation which gives a real result.

▪ Meanwhile, the relational operations denoted by ‘<’, ‘>’, ‘>=’, ‘<=’, ‘<>’ provide a logical
result

9
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.3 Variable Types:

❖ Integers
Algorithm Example_Integers
Example:
Variables:
Constant x ← 1
a : integer
b, c : integers
coefficient : integer

Begin
………
End
10
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.3 Variable Types:


Example:
❖ Real Numbers (floating-point: 1.0, 1.35, 1E+12, …)
Algorithm Example_Reals
▪ Represents the set of real numbers.
Variables:
▪ The ‘+’,’-‘, ‘*’, ‘/’ operations applied to real-type a : real
operands provide a result of the real typ. b,c : real
overall_average : real

Begin
………
End

11
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.3 Variable Types:


Example:
❖ Character
Algorithm Example_character
▪ This type encompasses all the characters necessary
for writing text. Variables:
a : character
b, c : characters
letter : character

Begin
………
End

12
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.3 Variable Types:


Example:
❖ Boolean: (True, False)
Algorithm Example_Boolean
▪ This type of variable can only take the values true
or false. Variables:
a : boolean
▪ The logical operators AND, OR, NOT, = applied to b,c : booleans
boolean operands, provide a boolean result. Admitted : boolean

Begin
………
End

13
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.4 Identifiers and Keywords:

▪ An identifier is the name of a variable, constant, or the name of an algorithm,

▪ It is a single word composed of numbers and characters, with the exception of a few
(depending on the programming language).

▪ A keyword is a reserved word that has a special meaning in a program, such as: Begin,
End, Real, Algorithm,Variables, If, Else, Integer, ....

Rules for writing identifiers:


✓ An identifier cannot be a keyword.
✓ An identifier must start with an alphabetical character.
✓ An identifier must not contain special characters like: ?, !, *, ...

14
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.5 Instructions:

▪ An instruction is a basic action that commands the computer to perform a calculation.

▪ A basic instruction can be an assignment or an arithmetic or logical operation. It can


also be a read (input) operation or a write (output) operation.

▪ Assignment: is the main elementary action, as it allows us to modify the value of a


variable. Its syntax is :

Variable ← value or variable ← expression

15
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.5 Instructions:

Examples: Algorithme Assignment 2

Variables:
Algorithm Assignment 1 A,B : integers
A←0
Variables: B←0 (Initialization)
A,B : integers
Begin
Begin A ← 10
A ← 10 B←5
B ← A+15 A ← A+ B

End End
16
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.5 Instructions:

❖ Write (Output)

▪ Write is the elementary action that allows an algorithm to provide results to the user. It
is done through the command (Function) Write.
Algorithm Writing 2
Examples:
Algorithm Writing 1 Variables:
A,B : integers
Variables:
……. Begin
Begin A ← 10
B ← A+15
Write (" Hello ! ") Write (B)
End
End 17
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.5 Instructions:

❖ Read (Input) Example:

▪ Read is an elementary action that allows specifying the Algorithm Reading


value of a variable through human intervention.
Variables:
▪ Read is done through the command (Function) Read. A,B,C : integers

Begin
A ← 10
Read (B)
C ← A+B
End

18
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

Exercise: (Knowing how to decipher a sequence of instructions)


▪ what the set of the following instructions does:

Algorithm Exercise

Variables:
A,B,C : integers

Begin
A←1
B ← 10
C ← A*2+B-3
Write (C)
End
19
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.6 Comments: Example:

Algorithm Comments
▪ A comment is an optional text (sentences)
located between the two symbols { } that Variables:
has no effect on the functioning of the A,B,C : integers
algorithm.
Begin
▪ It is used to explain the rationale behind {this program calculates the sum of two numbers}
certain instructions used in a program.
Read (A)
Read (B)
C ← A+B
Write (B)

End
20
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.6 Expressions:

▪ An expression is a combination of multiple operands (possibly functions).

▪ Arithmetic expressions: These involve arithmetic operators (+, -, /, *) as well as the


two operators DIV and MOD.

▪ Boolean (logical) expressions: These involve logical operators (AND, OR, NOT, ...) as
well as relational operators (>, <, <=, <>, ...).

Example : (a > b and b <= c) is a logical expression.

21
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.6 Expressions:

❖ Operator Precedence

▪ An expression is evaluated according to the precedence of operators, starting with the


highest priority.

▪ In cases where two operators have the same precedence, the one on the left is evaluated
first.

▪ Opening and closing parentheses are considered to be the highest priority operators.

22
I) FUNDAMENTALS AND BASIC CONCEPTS
2. FOUNDATION OF AN ALGORITHMIC LANGUAGE

2.6 Expressions:

❖ Operator Precedence

Precedence Operator Description

() Parentheses
+- plus, minus
Not Logical NOT
* / Mod Multiplication, Division, Modulus
Highest
+- Addition, Subtraction
< <= > >= Relational Operators
= Equality
AND Logical AND
OR Logical OR
Lowest ← Assignment Operators
23
2) CONTROL STRUCTURES
-> INTRODUCTION

A control structure is any action that allows a group of actions to be executed under
condition(s), thus guiding the flow of a program based on the fulfillment of these
conditions.

▪ There are several forms of control structures :


1. The conditional or alternative test 'If... Else'
2. The repetitive loop 'While'
3. The repetitive loop 'For'
4. The repetitive loop 'Repeat... Until'
5. The conditional test with multiple choices ‘Case -- of’

24
2) CONTROL STRUCTURES
1. CONDITIONAL OR ALTERNATIVE STATEMENT

▪ A condition is a statement that can be true or false. For example, a = b or n is even.


▪ In a program, depending on whether a condition is true or false, different actions can be
performed: these are referred to as conditional actions.
▪ The conditional structure is translated using the following instructions :

IF (condition) Then
Instructions (Action 1)
Else
Instructions (Action 2)
ENDIF

25
2) CONTROL STRUCTURES
1. CONDITIONAL OR ALTERNATIVE STATEMENT

▪ There is a second form of this conditional action:

IF (condition) Then
Instructions (Action 1)
ENDIF

▪ In this case :

➢ If the condition is verified, the action (or group of instructions) <Action 1> is executed then
the actions following the EndIf.

➢ On the other hand, if the condition is not verified, only the actions following the EndIf will be
executed.
26
2) CONTROL STRUCTURES
1. CONDITIONAL OR ALTERNATIVE STATEMENT

Example:
Algorithm IF_Example

Variables:
X : integer

Begin
Read (X)
IF (X ≥ 0) Then
Write (“X is positive!”)
Else
Write (“X is negative !”)
ENDIF
END
27
2) CONTROL STRUCTURES
2.THE 'WHILE' REPETITION LOOP

▪ The "While" loop specifies that an action (or group of instructions) should be repeated
as long as the condition remains true.

▪ The group of instructions <Actions> is repeated until the condition becomes false, so
the action part must be capable of modifying the parameters involved in the loop
condition in order to exit the loop.

▪ Syntax :

While (condition) Do
Instructions (Actions)
EndWhile

28
2) CONTROL STRUCTURES
2.THE 'WHILE' REPETITION LOOP

Example: Display of the first ten digits in decimal ?

Algorithm Example
Variables:
X : integer
Begin

X←0
While (X < 10) do
Write (X)
X←X+1
EndWhile
End

29
2) CONTROL STRUCTURES
3.THE 'FOR' REPETITION LOOP

▪ This loop is used when a task needs to be performed a known number of times

▪ The loop counter is incremented by 1 with each iteration.

▪ The action is re-executed until the value of the counter exceeds the final value.

▪ Syntax:

For (i=1 to n ) Do
Instructions (Actions)
EndFor

30
2) CONTROL STRUCTURES
3.THE 'FOR' REPETITION LOOP

Example: Display of the first ten digits in decimal ?

Algorithm Example

Variables:
X : integer

Begin
For (x=0 to 9 ) Do
Write (X)
EndFor
End

31
2) CONTROL STRUCTURES
4.THE 'REPEAT --- UNTIL' REPETITION LOOP

▪ This loop allows repeating an action (group of instructions) until the condition is
satisfied.

▪ The instructions inside the loop are executed at least once, unlike the "while" loop
where the condition is checked before execution.

▪ Syntax :

Repeat
Instructions (Actions)
Until (condition)

32
2) CONTROL STRUCTURES
4.THE 'REPEAT --- UNTIL' REPETITION LOOP

Example: Display of the first ten digits in decimal ?

Algorithme Example

Variables:
X : integer

Begin
X←0
Repeat
Write (X)
X←X+1
Until (X > 9)
End

33
2) CONTROL STRUCTURES
5.THE CONDITIONAL TEST WITH MULTIPLE CHOICES ‘CASE -- OF’

▪ The if-then-else-EndIf structure allows for two different choices.

▪ To allow for multiple possible choices, nested if-then-else-EndIf statements are used.

▪ Some programming languages offer a simpler solution. Here is the syntax:

Case integer expression or character of


list of values n° 1 : Actions n°1
list of values n° 2 : Actions n°2
…..
list of values n° n : Actions n°n
Default : other Actions
EndCase

34
2) CONTROL STRUCTURES
5.THE CONDITIONAL TEST WITH MULTIPLE CHOICES ‘CASE -- OF’

Exemple: Display of the number of days according to the month

Algorithm Example

Variables:
nbd, month : integers
bis: boolean

Begin
Read (month, bis)
Case month of
1, 3, 5, 7, 8, 10, 12 : nbd ← 31
4, 6, 9, 11 : nbd ← 30
2 : IF (bis = true) then nbd ← 29 Else nbd ← 28 EndIF
Default : nbd ← 0
EndCase
Write (nbd)
End
35
3) ARRAYS
1. INTRODUCTION

▪ Let's imagine that in a program, we need to work with 12 values simultaneously (for
instance, grades to calculate an average).

▪ Naturally, the only current solution we have is to declare twelve variables, like Notea,
Noteb, Notec, etc.

➢ This will lead to syntactical complexity and could increase the program's size.

▪ This is why programming allows us to group all these variables into a single structure,
where each value is identified by an index.

▪ Arrays are static programming structures; the size of the array must be specified
beforehand.

▪ The size of an array, once declared, cannot be changed.

36
3) ARRAYS
2. ONE-DIMENSIONAL ARRAY (VECTOR)

▪ A one-dimensional array is a collection of values that share the same variable name,
and each value is identified by a number called an index, which is used to access each
element of the array individually.

▪ Whenever we need to refer to an element of the array, we use the array's name followed
by the index of the element enclosed in square brackets.

▪ The diagram below illustrates a one-dimensional array:

37
3) ARRAYS
2. ONE-DIMENSIONAL ARRAY (VECTOR)

❖ Declaration of one-dimensional arrays

▪ A one-dimensional array is declared as shown below, specifying the number and type of
values it will contain:

Algorithm Declaration_Example

Variables:
Tab : array [1 .. 100] of integers
Grade : array [1 .. 10] of reals
Begin
……..
End
Remarks
• The cells of the array (elements) are numbered starting from 1.
• During the declaration of the array, the number of elements in the array is specified
38
3) ARRAYS
2. ONE-DIMENSIONAL ARRAY (VECTOR)

❖ Manipulation of one-dimensional arrays

➢ Reading (input), modification, and writing (output) of an element

Example
Algorithm manipulation

Variables:
Grade : array [1 .. 10] of reals
Begin
Read (Grade [1])
Grade [3] ← 15,5
Write (Grade[3])
End

39
3) ARRAYS
2. ONE-DIMENSIONAL ARRAY (VECTOR)

Exercise: write an algorithm that calculates a student's average


Algorithm Students_Average

Variables:
Solution 1:
Grade : array [1 .. 12] of reals
i: integer
Average: real
Begin
For (i=1 to 12 ) Do
Read (Grade[i])
EndFor

Average ← 0

Fro (i=1 to 12 ) Do
Average ← Average + Grade [i]
EndFor

Write (Average / 12)


End
40
3) ARRAYS
2. ONE-DIMENSIONAL ARRAY (VECTOR)

Exercise: write an algorithm that calculates a student's average

Algorithm manipulation

Solution 2: Variables:
Grade : array [1 .. 12] of reals
i: integer
Average: real
Begin
Average ← 0

For (i=1 to 12 ) Do
Read (Grade [i])
Average ← Average + Grade [i]
EndFor

Write (Average / 12)


End

41
3) ARRAYS
2. ONE-DIMENSIONAL ARRAY (VECTOR)

Exercise 2:

• Write an algorithm that reads and inverses the content an array of 10 integer elements.

Example:

1 2 5 0 9 11 4 6 10 3

3 10 6 4 11 9 0 5 2 1

42
3) ARRAYS
2. ONE-DIMENSIONAL ARRAY (VECTOR)

Solution: Algorithm Inverse

Variables:
X : array [1 .. 10] of integers
i,j,temp: integers
Begin
For (i=1 to 10 ) Do
Read (X [i])
EndFor

i ← 1 j ← 10

While (i<j) Do
temp ← X [i]
X [i] ← X [j]
X [j] ← temp
i←i+1
j←j-1
EndWhile
End
43
3) ARRAYS
3.TWO-DIMENSIONAL ARRAY (MATRIX)

▪ A two-dimensional array is a collection of values with the same variable name, identified
by two indexes (coordinates).

▪ The first index is used to represent rows, and the second index is for columns.

▪ The diagram below represents a two-dimensional array:

44
3) ARRAYS
3.TWO-DIMENSIONAL ARRAY (MATRIX)

❖ Declaration of two-dimensional arrays

▪ A two-dimensional array is declared in the following manner, specifying the number of


rows and columns as well as the type of values it will contain:

Algorithm Declaration_Example

Variables:
X : array [1..100, 1..100] of integers
Y : array [1..10, 1..47] of reals

Begin
……..
End

45
3) ARRAYS
3.TWO-DIMENSIONAL ARRAY (MATRIX)

❖ Manipulation of two-dimensional arrays

➢ Reading (input), modifying, and writing an element:

Example
Algorithm manipulation

Variables:
X : array [1..100, 1..100] of integers
Begin
Read (X [1, 1])
X [2, 3] ← 5
Write (X[50, 90])
End

46
3) ARRAYS
3.TWO-DIMENSIONAL ARRAY (MATRIX)

Exercise: write an algorithm that fills the matrix Mat[10, 20] with randomly entered
integer values.
Algorithme exercise
Variables:
Mat : array [1..10, 1..20] of integers
i, j : integers
Begin
For (i=1 to 10 ) Do
For (j=1 to 20 ) Do

Read (Mat [i, j])

EndFor
EndFor
End
47
3) ARRAYS
2. ONE-DIMENSIONAL ARRAY (VECTOR)

Exercise2: write an algorithm that reads 12 student grades with coefficients and
calculates the student's average grade.
Algorithm student_Average
10 3
Variables:
15 2
Grade : array [1 .. 12, 1..2] of reals
i,j: integers 9 4
Average, Coefficient : reals 17 2
Begin 8 3
Average ← 0 Coefficient ← 0
14 4
For (i=1 to 12 ) Do
For (j=1 to 2 ) Do 11 3
Read (Grade [i,j]) 16 5
EndFor
Average ← Average + (Grade [i,j]*Grade [i,j-1]) 12 2
Coefficient ← Coefficient + (Grade [i,j]) 10 4
EndFor
12 3
Write (Average / Coefficient)
13 4
End
48
3) ARRAYS
3.TWO-DIMENSIONAL ARRAY (MATRIX)

Exercise 3: Write an algorithm that fills the integer matrix Mat[10, 10] with randomly
entered integer values and then calculate the sum of its diagonal.
Algorithme diagonal
Variables:
Mat : array [1..10, 1..10] of integers
i, j, sum : integers
Begin
For (i=1 to 10 ) Do
For (j=1 to 10 ) Do
Read (Mat [i, j])
EndFor
EndFor
sum ← 0
For (i=1 to 10 ) Do
sum ← sum + Mat [i, i]
EndFor
Write (sum)
End
49
3) ARRAYS
4. N-DIMENSIONAL ARRAYS

❖ Declaration of N-Dimensional Arrays

▪ An N-dimensional array is declared in the following manner, specifying the number and
type of values it will contain:

Algorithm Declaration_Example

Variables:
X : array [1..100, 1..100, 1…300] of integers ;
Y : array [1..10, 1..47, 1..12, 1..7] of reals ;

Begin
……..
End

50
4) FUNCTIONS AND PROCEDURES
1. INTRODUCTION

▪ Functions and procedures, also known as subprograms, provide programmers with a


simple means of abstraction by allowing them to name a sequence of instructions and
call it as many times as necessary within the same program.

▪ Furthermore, programming languages allow passing data to the procedure or function.


➢ The values of these data can vary from one call to another, and this mechanism is
called parameter passing.

▪ A subprogram (function or procedure) has the same structure as a program,


➢ The only significant differences are the concepts of parameters and local variables.

51
4) FUNCTIONS AND PROCEDURES
1. FUNCTIONS

▪ A function is a collection of instructions that form a subprogram.

▪ Functions in algorithmics (programming) are similar to those in mathematics. Every time


a function is called, it returns a value to the calling program, which is the result of the
processing performed by the function's instructions.

▪ A function can return any basic data type.

52
4) FUNCTIONS AND PROCEDURES
1. FUNCTIONS

❖ Function Declaration
▪ The general structure of a function is as follows :

Function FunctionName (variable1 : type1, variable2 : type2, …variableN : typeN) : type


Variables: variable1, …variableN : type {declaration of function-specific variables}

Begin

Instructions {function body}

End

Note : At the end of a function, the result of the processing must be returned.

53
4) FUNCTIONS AND PROCEDURES
1. FUNCTIONS

❖ Local Variables and Global Variables

▪ Variables declared in the declaration part of a function are called local variables.

▪ They are unknown to the main program where the function has been declared.

▪ Variables declared in the main program are known to the functions declared in the same
program.They are called global variables.

54
4) FUNCTIONS AND PROCEDURES
1. FUNCTIONS

❖ Formal Parameters and Actual Parameters

▪ The parameters described in the function header during declaration are called formal
parameters. They serve to represent the structure and operation of the function.

▪ On the other hand, the values that replace them in function calls are called actual
parameters or actual arguments.

❖ Function Call

▪ To call a function, you place the function name to the right of a variable assignment, often
referred to as a return variable. The syntax is:

Variable ← Function_Name(parameters)

55
4) FUNCTIONS AND PROCEDURES
1. FUNCTIONS

❖ Usage of Functions
▪ Once declared, a function can be called from the main program or another function.

Exercise 1 : Write an algorithm that calls a function to calculate the Cnp.

56
4) FUNCTIONS AND PROCEDURES
1. FUNCTIONS

Algorithm CNPCalculation

Variables:
cnp, n, p: integers
Function Factorial (n : integer) : integer
Variables: t, i : integer
Begin
t←1
For (i =1 to n) Do
t←t*i
EndFor
Return (t)
End

Begin
Write ("Give the value of n and p" )
Read (n, p)
Cnp ← Factorial(n) / (Factorial(n-p) * Factorial(p) )
Write ("cnp = ", cnp)
End
57
4) FUNCTIONS AND PROCEDURES
1. FUNCTIONS

Exercise 2 :

Write an algorithm that calculates the greatest common divisor (GCD) of two positive
integer numbers.

58
4) FUNCTIONS AND PROCEDURES
1. FUNCTIONS

Algorithm GCDCalculator

Variables:
x,y: integers

Function GCD (a : integer, b : integer) : integer


Begin
While (a < > b) Do
IF (a > b) Then a←a–b Else b ← b – a EndIF
EndWhile
Return (a)
End

Begin
Read (x, y)
Write ("GCD = ", GCD(x,y))
End

59
4) FUNCTIONS AND PROCEDURES
2. PROCEDURES

▪ The second type of subroutine is called a procedure.

▪ A procedure is very similar to a function except that it may not return any result or may
return multiple results.

❖ Declaration of a Procedure

Procedure ProcedureName (InputVar1 : type1, …InputVarN : typeN, OutputVar1: Type1,…, OutputVarN: typeN)
Variables: variable1, …VariableN : type {declaration of procedure-specific variables}

Begin

Instructions {body of the procedure}


End

60
4) FUNCTIONS AND PROCEDURES
2. PROCEDURES

Notes

▪ The last instructions in a procedure are usually reserved for assigning the results of the
processing done by the procedure to its output parameters.

▪ The concepts of global and local variables, formal and actual parameters for procedures
have the same meanings as for functions.

▪ Calling a procedure is done by writing its name and replacing the formal parameters with
the actual parameters.

61
4) FUNCTIONS AND PROCEDURES
2. PROCEDURES

Exercise 1: write an algorithm that calls a procedure to calculate the maximum of


two integer values.
Algorithm ExerciseMax

Variables:
x, y, Max: Integers
Procedure Maximum (a: integer, b: integer, c: integer)
Begin

IF (a ≥ b) Then c ← a Else c ← b EndIF


End

Begin
Read (x, y)
Maximum (x, y, Max)
Write (Max)
End

62
4) FUNCTIONS AND PROCEDURES
2. PROCEDURES

Exercise 2: write an algorithm that that uses a procedure to calculate the area of a
circle based on the radius entered by the user.
Algorithm CircleAreaCalculator
Constant PI ← 3.14159
Variables:
x,y: reals
Procedure CircleArea (R: real, Area: real)
Begin

Area ← PI * R * R
End

Begin
Read (x)
CircleArea (x, y)
Write (" Circle Area = ", y)
End

63
4) FUNCTIONS AND PROCEDURES
3. CONCLUSION

Conclusion:

Subprograms (functions and procedures) are program segments that are often
repeated either within the same program or across multiple programs,

➢ Therefore, it is preferable to write them once and use them as needed. They
also help simplify the development of large programs.

64

You might also like