Mi1an Algo-Exercices Corriges (1) .FR - en
Mi1an Algo-Exercices Corriges (1) .FR - en
com
Brahim BESSAA
1st Year MI
September 2017
Preface
After several years of teaching the “Algorithmics” module of the first year of the degree
(MI) and given the difficulties encountered by students in this module, I tried to provide them
with training support to help them master this module.
This book brings together exercises from the series of tutorials and exams (with corrections)
of the Algorithmic module of the first year MI (USTHB). In this book I give detailed solutions to the
proposed exercises, but it should in no case replace the TD sessions, where students can discuss
the solutions and see other proposed solutions. In fact, the TD instructor can always give more
details and explanations.
A positive use of this work therefore consists of encouraging students to prepare their series of
exercises, compare their solutions with those proposed and plan questions to ask during tutorial
sessions.
Finally, the book is a first version of a personal effort. I await from dear students and
colleagues their remarks and suggestions in order to improve it in the next versions.
September 2017.
bbessaa@yahoo.fr
Summary
The Recordings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
The Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Linked Lists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Control Structures (Conditional – Iterative)
EXERCISE 1
Write an algorithm that asks the user for a number, then calculates and displays the square of that number.
AlgorithmSquare ;
VarX,X2 :real ;
Beginning
To write('Give a reel');
Read(X);
X2←X*X ;
To write('The square of ',X,' is: ',X2) ;
END.
EXERCISE 2
A copy shop charges 2 DA for the first ten photocopies, 1.50 DA for the next twenty, and 1 DA for more.
Write an algorithm that asks the user how many photocopies were made and then displays the
corresponding amount.
AlgorithmBill ;
ConstP1=2 ; P2=1.5 ; P3=1 ;
Var Mount:real;
Nbc:integer;
Beginning
Fsi;
To write('The amount to be paid is: ',Mont) ;
END.
EXERCISE 3
AlgorithmSeason;
VarM: integer;
Beginning
CaseMWorth
3,4,5:To write('The season is: SPRING');
6,7,8:To write('The season is: SUMMER');
9,10,11:To write('The season is: AUTUMN');
12,1,2:To write('The season is: WINTER');
FinCas;
END.
EXERCISE 4
Write an algorithm to solve each of the following problems:
1-
AlgorithmSum ;
VarI,N,S: integer;
Beginning
To write('Give an integer N') ;Read(N) ;
S ←0 ;
ForI ←1hasN-1
Do
S ←S+I;
Do;
To write('The sum of the',N,' first numbers is: ',S) ;
END.
2-
AlgorithmMaxMin;
VarI,N,Max,Min,X:integer;
Beginning
To write('Give an integer N>0');
Repeat Read(N) ;UntilN>0 ;
/* Read the first element, then initialize the Min and Max to that value
Read(X) ; Max←X ; Min←X ; ForI ←2hasN
Do
/* read the rest of the items and update the Min and Max
Read(X);
IfMax<X SOMax←X
Otherwise IfMin>XSOMin←XFsi
Fsi;
Do;
To write('The Minimum of the values is: ',Min,' the Maximum is: ',Max) ;
END.
3-
AlgorithmQuotReste;
VarA,B,Q,R: integer;
Beginning
To write('Give two integers A and B');
Read(A,B);
Q ←0 ; R ←A ;
As long asR>B
Do
Q ←Q+1;
R ←RB;
Do;
To write('The Quotient of A/B is: ',Q, ' The remainder of A/Best: ',R) ;
END.
4-
AlgorithmProduct ;
VarA,B,P,I: integer;
Beginning
To write('Give two integers A and B');
Read(A,B);
IfA=0 or B=0
SOP←0
OtherwiseP←0 ;/*initialize the product to 0
ForI ←1hasB
Do
P←P+A ;
Do
Fsi;
To write('The product A*B is: ',P);
END.
We can optimize the solution by choosing the loop with the fewest iterations:
AlgorithmProduct ;
VarA,B,P,I: integer;
Beginning
To write('Give two integers A and B');
Read(A,B);
IfA=0 or B=0
SOP←0
Otherwise IfA>B
SO P←A ;/*We can initialize the product to A and start the loop at 2
ForI ←2hasB
Do
P←P+A ;
Do
OtherwiseP←B ;
ForI ←2hasHAS
Do
P←P+B ;
Do
Fsi;
To write('The product A*B is: ',P);
END.
5-
AlgorithmAdivB;
VarA,B,R: integer;
Beginning
To write('Give two positive integers A,B');
Repeat Read(A,B);UntilA>0 and B>0 ; R
←A ;
As long asR≥0DoR ←RB;Do;
IfR=0So Write(A,' is divisible by ',B)
Otherwise Write(A,' is not divisible by ',B)
Fsi;
END.
6-
AlgorithmDividers;
VarX,M,I: integer;
Beginning
To write('Give an integer X');
Read(X);
To write('The divisors of ',X,' are :') ;
/*We loop from 1 to half of X, because after half there is no more divisor except X /*We can use
the integer division function DIV and the remainder function of this division MOD M←XDIV2 ;
ForI ←1hasM
Do
IfXMODI=0So Write(I)Fsi;
Do;
To write(X);
END.
7-
AlgorithmFirst;
Var X,M,I: integer;
Pr:boolean;
Beginning
Do
Fsi;
IfPrSo Write(X,' is prime')Otherwise Write(X,' is not prime')Fsi;
END.
8-
AlgorithmSumChiff;
VarN,S,R: integer;
Beginning
To write('Give a natural integer N');
Repeat Read(N) ;UntilN≥0 ; S←0 ; R
←0 ;
As long asR>0
Do S←S+RMOD10;
R← RDIV10;
Do;
To write('The sum of the digits that make up ',N,' is :',S) ;
END.
EXERCISE 5
Write an algorithm that allows the user to enter a character sequence ending in '*', and which displays at the
end the number of times the letter ' appearsHAS'.
NbA ←0 ;
Repeat
Read(ch);
Ifch='A'SONbA ←NbA+1Fsi; Until
ch='*' ;
To write('Number of appearances of A is:',NbA);
END.
AlgorithmAppearance;
Var ch: character;
NbA: integer;
Beginning
NbA ←0 ;
Ch ←'X' ;/*Initialize Ch to a character other than '*'
Tank ch<>'*'
Do
Read(ch);/*reading is done before
processing Ifch='A'SONbA ←NbA+1Fsi;
Do;
To write('Number of appearances of A is:',NbA);
END.
AlgorithmAppearance;
Var ch: character;
NbA: integer;
Beginning
NbA ←0 ;
Read(ch);/*read the first value of ch before the loop
Tank ch<>'*'
Do
Ifch='A'SONbA ←NbA+1Fsi;
Read(ch);/*The following reading is done after processing
Do;
To write('Number of appearances of A is:',NbA);
END.
EXERCISE 6
Write an algorithm to calculate the value of the expression E,
such that E=(1+2)x(1+2+3)x(1+2+3+4)x…x(1+2+3+…+(N-2)+(N-1)+N), and (N≥2).
AlgorithmSumE;
VarI,J,N,E,S: integer;
Beginning
Read(N) ;
E ←1 ;
S ←1;
ForI ←2hasN
Do
S ←S+I;
E ←E*S ;
Do;
To write('E=',E) ;
END.
EXERCISE 7
Write an algorithm to calculate the value of the expression E,
ퟏ ퟏ
푬 = ퟏ +ퟏ+ + ⋯+ , with (N≥2).
ퟏퟐ ퟏퟐퟑ ퟏퟐퟑ⋯푵
AlgorithmSumE;
VarI,J,N,S: integer;
E:reel;
Beginning
RepeatRead(N);UntilN>=2 ; E
←1 ;S ←1;
ForI ←2hasNDo
S ←S+I;
E ←E+1/S ;
Do;
To write('E=',E) ;
END.
EXERCISE 8
Write an algorithm to calculate the value of the Nth term (N<100) of the sequence UNdefined by:
푈 = 2, 푈 = 3, 푈 = 푈 − 푈
AlgorithmFollowing ;
Var I,N: integer;
X,Y,A :real ;
Beginning
To write('Give 0<N<100') ;
Repeat Read(N)Until(N>0)And(N<100); X
← 2;
Y←3 ;
/* Attention the 1st term (N=1) corresponds to U0, the recurrence starts from 3 For
I←3hasN
Do
A ← (2/3)*Y-(1/3)*X ;/*we must linearize the expression
X←Y;
Y ← One ;/*pay attention to the order between the last two assignments
Do;
CaseNWorth
1: A ← X ;
2: A ← Y ;
FinCas;
To write('The ',N,' th term is: ',One) ;
END.
EXERCISE 9
Write an algorithm that determines and displays the Nthvalue of the sequence (UN) knowing that
Algorithmfollowing;
VarX,Y,Z,A,I,N:integer;
Beginning
To write('Give an integer');
Repeat Read(N) ;UntilN≥0 ; X
←0 ;
Y←1 ;
Z←2 ;
ForI←3hasNDo
A←Z+X ;
X←Y ; Y←Z ; Z←A ; Do;
CaseNWorth
0: A←X;
1: A←Y;
2: A←Z;
Farms;
To write('The term One is:',One);
END.
EXERCISE 10
Write an algorithm to convert an integer N written in binary form to its decimal value.
Algorithmconversion ;
VarVB,B,D,P2:integer;
Beginning
To write('Give an integer in binary');
Repeat Read(VB)UntilVB>=0 ;
B ← VB ;/*VB backup for display
P2 ← 1 ;/*P2 contains the power of 2, initially 20=1 D ←
0;
Repeat
D ← D + (BMOD10)*P2 ;/*retrieve the coefficient = the rightmost digit of the number P
← 2 * P2 ;/*calculation of the next power of 2 B ← BDIV10 ;/*to move to the next
coefficient UntilB=0 ;
EXERCISE 11
Write an algorithm that calculates the N-order sum of푺풏defined as follows using only the
basic operators (without the use of the power operator ).
푵
(−ퟏ)풊 ퟏ
푺풏 =
풙풊
풊ퟎ
AlgorithmSumSuite;
Var I,N,K:integer;
Px,X,Sn :real ;
Beginning
To write('Give an integer');
Repeat Read(N)UntilN>=0 ; To
write('Give a real'); Read(X);
Sn←Sn+K/Px ;
Do;
To write('The sum Sn= ', Sn) ;
END.
EXERCISE 1
Write the parameterized actions (procedure or function) to solve the following problems: 1-
Calculation of the sum of two whole numbers.
2- Calculation of the factorial of N (N!).
3- Check if an integer A divides an integer B.
4- Calculation of the quotient and remainder of the integer division of two integers A and
B. 5- Check if a given character is a vowel (vowels: 'a', 'e', 'i', 'o', 'u', 'y').
6- Allows you to swap (exchange) the contents of two real variables. 7-
Given an integer A, calculates its absolute value.
1-FunctionSum(x,y:integer):integer;
Beginning
Sum ← x+y ;
END;
2- FunctionFact(x:integer):integer;
Var I,F: integer;
Beginning
F←1 ;/*we can use the function name directly instead of F ForI
←1 to x
DoF ← F*I ;Do; Fact
←F;
END;
3- FunctionDivide(A,B:integer):boolean;
Beginning
Divide ← False ;
IfB mod A = 0SODivide ← TrueFsi;
END;
4- ProcedureQuotRest(E/ A,B:integer; S/ Q,R:integer);
Beginning
Q←0;R←A;
As long asR>= B
Do
R ← R mod B ;
Q ← Q+1 ;
Do;
END;
5- FunctionVowel(C:character):boolean;
Beginning
Vowel ← False ;
CaseCWorth
'a', 'e', 'i', 'o', 'u', 'y': Vowel ← True ;
Farms;
END;
6- ProcedurePermute(I/O/ A,B:integer);
VarC:entire:
Beginning
C←A;A←B;B←C;
END;
7- FunctionVabs(A:integer):integer;
Beginning
Vabs ← A ;
IfA<0SOVabs ← AFsi;
END;
EXERCISE 2
1- Write an APSquare vverifying whether a natural integer is a perfect square, using only the
basic operators, and returns its root in the favorable case. (Hint: X is a perfect square if there exists an
integer i such that X = i * i.)
2- Write an algorithm which, among N natural integers, calculates the sum and the product of the square roots of the
perfect square integers. Then it checks whether the sum and the product are perfect squares.
END;
2- AlgorithmCalculation ;
VarI,N,S,P,X,Rac:integer; CParfiat:boolen;
ProcedureSquare(E/ A:integer; S/ CP::booleen; S/ RC:integer);
/* we resume the declaration of the procedure
-----
Beginning
EXERCISE 3
1- Write a function that returns True if the character passed as a parameter is equal to -o- or -O- (whoever wants
say Yes), and False otherwise.
2- Write a parameterized action that allows you to display the multiplication table from 1 to 9 of a number
positive integer. Then, using the previous parameterized actions, write an algorithm to
display the multiplication table of an integer to the user for as long as he wants (until the
answer is wrong).
1- FunctionResponse(C:character):boolean;
Beginning
Answer ← False;
IfC='o' or C='O 'SOAnswer ← TrueFsi;
END;
2- ProcedureDisplayTable(A:integer);
VarI: integer;
Beginning
ForI ← to 9
DoWrite(A,'x',I,'=',A*I) ;Do;
END;
3- AlgorithmTableM ;
VarA: integer; Rep: character;
FunctionResponse(C:character):boolean;
.......
ProcedureDisplayTable(A:integer);
.......
Beginning
Repeat
Write('Give an integer');
Read(A);
DisplayTable(A);
Write('Do you want to continue Y/N');
Read(Rep);
UntilNo Response(rep);
END.
EXERCISE 4
Write an algorithm that displays all numbers less than 500 equal to the sum of the cubes of their
digits. We will use a UNIT function, and a CUBE function.
Example: 153 = 13+ 53+ 33= 1 + 125 + 27
AlgorithmSumCube ;
VarA,B,S: integer;
FunctionUnite(X:integer):integer;
Beginning
Unite ← X mod 10 ;
END;
FunctionCube(X:integer):integer;
Beginning
Cube ← X*X*X ;
END;
Beginning
ForA← 0 to 500
Do
S← 0; B ← A;
RepeatS← S + Cube(Unit(B)); B ← B div 10UntilB=0;
IfS=ASOWrite(A,' is equal to the sum of the cubes of its digits')Fsi;
Do;
END.
EXERCISE 5
Write an algorithm that displays all perfect numbers less than 10000. Knowing that a positive integer
(N) is perfect if it is equal to the sum of its divisors (<N). We will write a Boolean function, called
PERFECT, to check if the number is perfect or not perfect.
Examples: 6 — which is equal to 1 + 2 + 3 —
and 28 — which is equal to 1 + 2 + 4 + 7 + 14 — are perfect numbers.
AlgorithmPerfectNumber;
VarA: integer;
FunctionPerfect(X:integer):boolean; Var
I,S: integer; Beginning
S←0;
ForI ← 1 to X div 2
Do IfX mod I = 0SOS ← S+IFsi; Do;
ForA← 1 to 10000
Do IfPerfect(A)SOWrite(A,' is perfect')Fsi; Do;
END.
EXERCISE 6
For this exercise, we do not have a predefined function in algorithms processing the characters (next, previous,
character code, character of the code, etc.), so either we use aCase Worthwith the 26 possible cases, or we use a
loop as follows.
FunctionMinus(C:character):character; Var
I,J: integer; X: character; Beginning
EXERCISE 7
In this exercise, according to the second question, it is better to write a procedure that returns the number of
divisors of the input integer and a boolean to check if it is prime or not.
1- FunctionFirst(E/X: integer):boolean;
VarI,M:integer;
Beginning
IfX=1SOFirst ← False
Otherwise M ← X DIV 2 ; I ← 2 ; First ← True ; As
long asI≤M and Prime Do
Do;
Fsi;
END;
2- FunctionSemiFirst(E/X: int):booleen; Var
I,M:integer;
Beginning
IfFirst(X)
SO SemiFirst ← False
Otherwise M ← X DIV 2 ; I ← 2 ;
SemiFirst ← True ; As long
asI≤M and SemiFirst Do
Fsi;
I←I+1 ;
Do;
Fsi;
END;
3- For this question, it is about finding a formula to generate numbers of the formabcabcin order to
optimize the algorithm (minimize the number of iterations).
We have:
So to generate these numbers you just have to generate a part (abc), then multiply it by 1001.
AlgorithmNumber ;
Vara,b,c,X,NBDiv:integer; Pr:booleen;
FunctionFirst(X : integer): boolean;
---------
FunctionSemiFirst(X : integer): boolean;
---------
Beginning
Do;
Do;
END.
EXERCISE 8
FunctionBIN(X:integer):integer; Var
R,P: integer; Beginning
P ← 1 ; BIN ← 0 ;
Repeat
R ← X mod 2 ;
BIN ← BIN + R*P; P
← P*10 ;
X ← X div 2 ;
UntilX=0 ;
END.
EXERCISE 9
Write a functionROOT2which calculates the square root of a positive number using the following
formula: X = (X + )
FunctionRoot2(A:real):real;
Const ER=0.001;
VarX,Y,D :real ;
Beginning
X←A;
Repeat
Y ← 0.5*(X+A/X); D
← YX ;
IfD<0SOD ← -DFsi; X ←
Y;
UntilD<ER ;
Root2 ← Y ;
END;
EXERCISE 10
Unroll the following algorithm, giving the different values of the expected results in the order in which
the algorithm is executed.
AlgorithmCall ;
VarR, V: integer;
FunctionCALCULATION ( X : INTEGER ) : integer ;
VarR: integer; Beginning
R←X+V;
V← R – 2 ;
CALCULATION ← R + 2 *
V ; Write ( R , V ) ;
END;
Beginning
V←5;
R ← CALCULATION(V) ; Write ( R , V ) ; R
← CALCULATION( V ) ; Write ( R , V ) ; R ←
10 ;
V ← CALCULATION ( R ) ; Write ( R , V ) ;
END.
Overall Function
Action Display
R V CALCULATION X R (local)
V ←5 5
CALCULATION(V) 5
R ← X+V 10
V ← R-2 8
CALCULATION ← R+2*V 26
WRITE(R,V) 10 8
R← CALCUL 26
WRITE(R,V) 26 8
CALCULATION(V) 8
R ← X+V 16
V ← R-2 14
CALCULATION ← R+2*V 44
WRITE(R,V) 16 14
R← CALCUL 44
WRITE(R,V) 44 14
R ← 10 10
CALCULATION(R) 10
R ← X+V 24
V ← R-2 22
CALCULATION ← R+2*V 68
WRITE(R,V) 24 22
V ← CALCUL 68
WRITE(R,V) 10 68
EXERCISE 1
Let T be a vector (one-dimensional array) containing N integers (N≤100). Write the algorithms for:
1- AlgorithmMinMax ;
Var T: Array[1..100] of integer;
I,N,Max,Min,S: integer; Avg: real;
Beginning
2- AlgorithmProd;
Var T: Array[1..100] of integer;
I,N,P,Nbp: integer;
Beginning
P←1 ; Nbp←0 ;
/*Reading elements of T and processing at the same
time ForI←1 to NDo
Read(T[I]) ;
IfT[I]>0SONbp←Nbp+1Fsi; P←P*
T[I] ;
Do;
Write('Product=',P,'Nb positive values=',Nbp);
END.
3- AlgorithmProd;
Var T1,T2,T3:Array[1..100] of integer;
I,N,PS:integer;
Beginning
ForI←1 to NDo
T3[I]←T1[I]+ T2[I];
PS←PS+ T1[I]* T2[I];
Do;
Write('Scalar Product=',PS); Write('Sum
of vectors'); ForI←1 to NDoWrite
(T3[I]);Do;
END.
4- AlgorithmPosition ;
Var T,Pos:Array[1..100] of integer;
I,J,N,Val:integer;
Beginning
ForI←1 to NDo
IfT[I]=ValSOJ←J+1 ;Pos[J]←IFsi;
Do;
IfJ=0SOWrite(Val,'not found')
OtherwiseWrite(Val,'found at positions:');
ForI←1 to JDoWrite (Pos[I]);Do;
Fsi;
/* If we initialize J to 1, its incrementation is done after the assignment and the /
*dimension of Pos becomes J-1
END.
5- AlgorithmReverse ;
Var T: Array[1..100] of integer;
I,J,X,N:integer;
Beginning
I←1 ; J←N ;
As long asI<J
Do
X←T[I] ; T[I]←T[J]; T[J]←X;
I←I+1 ; J←J-1;
Do;
/*Display the new table T ForI←1 to
NDoWrite(T[I]) ;Do;
END.
6- AlgorithmDeleteZero;
Var T: Array[1..100] of integer;
I,J,N: integer;
Beginning
Solution 2:
AlgorithmDeleteZero2;
Var T: Array[1..100] of integer;
I,J,NBN,N:integer;
Beginning
Do
IfT[J]=0
SO NBN←NBN+1/*number of null values /
Otherwise *move element
T[I]← T[J] ; I←I+1
Fsi;
J←J+1;
Do;
N←N-NBN ;/*change the size of T
/*Display the new table T ForI←1 to
NDoWrite(T[I]) ;Do;
END.
7- AlgorithmNegPuisPos ;
Var T: Array[1..100] of integer;
I,J,N,X:integer;
Beginning
EXERCISE 2
Write an algorithm that allows a vector T of N (N≤250) integers assumed to be positive to be split into two
vectors T1 and T2 containing respectively the even and odd numbers of T.
AlgorithmProd;
Var T1,T2,T : Array[1..250] of integer ;
I,J,K,N : integer ;
Beginning
EXERCISE 3
Let T be a vector of N integers (N≤200). Write an algorithm that determines the number of successions of
two particular values (V1 and V2) in the vector.
AlgorithmRepetition ;
Var T: Array[1..200] of integer;
I,N,V1,V2,NBrep: integer;
Beginning
I←1 ; NBrep←0 ;
As long asI<N
Do
IfT[I]=V1 and T[I+1]=V2
SO NBrep← NBrep+1 ; I←I+2 I
Otherwise ←I+1
Fsi;
Do;
Write('Number of successions of values',V1,V2,' is :',NBrep);
END.
EXERCISE 4
Let two sorted integer vectors V1 (N integers, N≤100) and V2 (M integers, M≤150).
Write a procedure that merges these two vectors into another sorted vector V3 without repeating
identical values.
AlgorithmFusion2;
Var A:Array[1..100] of integer; B:Array[1..150] of integer;
C:Array[1..250] of integer;
I,J,K,N,M: integer;
Beginning
EXERCISE 5
Let T be an array of N numbers (N≤50). Write an algorithm that reverses, in T, the first increasing
sequence of numbers.
AlgorithmVector ;
Var T: Array[1..50] of integer;
I,J,X,N: integer;
Beginning
EXERCISE 6
Let A(N, M) be a matrix of characters (N≤20 and M≤30). Write an algorithm that
1- Search for an element in matrix A.
2- Calculates the number of vowels belonging to matrix A.
AlgorithmMatrix;
VarI,J,N,M,Val,Nbv:integer; Exists:booleen;
A : Array[1..20,1..30] of integer;
AT : Array[1..20,1..30] of integer;
Start
RepeatRead(N);Until(N>0) and (N≤20);
RepeatRead(M);Until(M>0) and (M≤30); //
Reading the Matrix
ForI ←1 to NDo ForJ ←1 to MDo
Read(A[I,J]);
Do;
Do;
Write('Give Val'); Read(Val); /
*Search for Val
Exists←False; I←1 ; Tank I
≤N and Non Exist Do
J←1 ;
While J ≤M and Does Not Exist
Do
IfA[I,J]=ValSOExists←TrueFsi; J←J+1 ;
Do;
I←I+1 ;
Do;
IfExistsSOWrite(Val,'Exists')OtherwiseWrite(Val,'Not Found')Fsi; /*
number of vowels in A Nbv←0 ;
EXERCISE 7
Let A(N, N) be a square matrix of integers (N≤25). Write two of the parameterized actions allowing to:
1- Calculate the trace of matrix A. (The trace is the sum of the elements of the main diagonal).
2- Determine the maximum and its position, of the values of the two diagonals (main and secondary).
AlgorithmTrace ;
VarI,J,N,Max,Lmax,Cmax,Tr:integer; A: Array[1..25,1..25] of integer;
Beginning
ForI ←1 to N
Do IfMax< A[I,I])SOMax← A[I,I]; Cmax←I;Lmax←IFsi; /*Diag Main
/*Secondary diag – renter relation index I------- N+1-I
IfMax< A[I,N+1-I])SOMax← A[I,N+1-I]; Cmax←N+1-I;Lmax←IFsi;
Do;
Write('Max=',Max,'Row Position:',Lmax,'Column:',Cmax);
END.
EXERCISE 8
Given a matrix A(N, M) of integers (N≤20 and M≤30), write an algorithm which:
- Calculates and saves the sum of each column,
- Determines the Jmin position of the minimum sum and the Jmax position of the sum maximum.
- Swaps the two columns of indices Jmin and Jmax of matrix A if Jmin > Jmax.
AlgorithmMatrix;
VarI,J,N,M,Jmin,Jmax,X:integer;
A: Array[1..20,1..30] of integer; Sum: Table[1..30] of whole
Start
RepeatRead(N);Until(N>0) and (N≤20);
RepeatRead(M);Until(M>0) and (M≤30); //
Reading the Matrix
ForI ←1 to NDo ForJ ←1 to MDoRead(A[I,J]);Do;Do; //calculate and
save the sum of each col ForJ ←1 to M
Do Som[J]←0 ;
ForI ←1 to N
Do
Som[J]← Som[J]+ A[I,J];
Do;
Do;
ForJ ←1 to MDoWrite(Som[J])Do; Jmin
←Som[1]; Jmax← Som[1]; ForJ ←1 to M
Fsi;
END.
EXERCISE 9
Do;
M←M-1/*decrease the number of columns without moving to the next column, because the
/* shifted column can also be the same as V1
OtherwiseJ←J+1
Fsi;
Do;
EXERCISE 10
1- Function Presence(CH:string[200];C:character):boolean;
VarT,I: integer; Pr: boolean;
Beginning
T←Size(CH); Pr←False; I←1 ;
As long asI≤T and Not PrDo IfCH[I]=CSOPr←TrueFsi;I←I+1 ;Do;
Presence ←Pr ;
END;
2- Function NBVowel(CH:string[200]):integer;
VarT,I,Nbv:integer;
Beginning
T←Size(CH); Nbv←0; ForI
←1 to T
Make CaseCH[I]Worth
'a','e','i','o','u','y': Nbv←Nbv+1;
Farms;
Do;
NBVowel ←Nbv ;
END;
3- Function TouVoyelle(PH:string[200]):boolean;
VarT,I:integer; CV:string[6];
Beginning
T←Size(PH); CV←'aeiouy' ; ForI
←1 to T
Make CasePH[I]Worth
'a' :CV[1]←'X' ;
'e': CV[2]←'X'; 'i':
CV[3]←'X'; 'o':
CV[4]←'X'; 'u':
CV[5]←'X'; 'y':
CV[6]←'X'; Farms
;
Do;
IfCV='XXXXXX'SOTouVoyelle ←TrueOtherwiseTouVoyelle ←FalseFsi;
END;
EXERCISE 11
SOI←1 ;
As long asI≤(T-Ts+1) and Not EX
Do J←I; K←1; EX←True; As
long asK≤Ts and EX Do
IfCH[J]<>SH[K]SOEX←FalseFsi; J←J+1 ;
K←K+1 ;
Do;
I←I+1 ;
Do;
Fsi;
SHexiste←EX ;
END;
2- Procedure DeleteNP(I/O/ CH:string[250], I/N,P:integer);
VarT,I:integer; CHI:string[250];
Beginning
T←Size(CH);
IfP≤T
SOCHI←'' ;/*initialize empty
ForI ←1 to P-1DoCHI[I]←CH[I] ;Do;/*copy the part before P /*Add
the characters after the N to be deleted
If(P+N)>TSON←TPFsi;/*if there are less than N characters left, we delete
all ForI←P+N at TDoCHI←CHI+CH[I] ;Do; CH←CHI ;
Fsi;
END;
3- Palindrome function (CH:string[250]):boolean;
VarI,J: integer; Pal: boolean;
Beginning
I←1 ; J←Size(CH); Pal←True; As
long asI<J and Pal Do
IfCH[I]<>CH[J]SOPal←FalseFsi; I
←I+1 ; J←J-1 ;
Do;
Palindrome←Pal;
END;
EXERCISE 12
Write an algorithm that counts the number of characters, words, and sentences in a text. Words are
separated by spaces and sentences are separated by a period. (Not counting the separators: space and
period)
AlgorithmText ;
VarTX:chain;
T,NbC,NbM,NbP,I:integer;
Beginning
EXERCISE 13
Write an algorithm that reads two words and determines if they are anagrams. Knowing that a word is said to be
an anagram of another word if they use (are formed by) the same letters.
Examples :
DOG anagram of CHINA, NICHE, AIMER
anagram of MAIRE, MARIE, RAMIE, FREEZE is
not anagram of ALGER, …
AlgorithmAnagram;
VarM1,M2:chain;
Procedure SORT(I/O/CH:string); Var
I,J,T:entire; X:character; Beginning
T←Size(CH);
ForI←1 to T-1
Do ForJ←I+1 to T
Do IfCH[I]>CH[J]
SO X←CH[I] ; CH[I]←CH[J]; CH[J]←X;
Fsi;
Do;
Do;
END;
Beginning
Write('give 2 words');
Read(M1,M2);
SORT(M1); SORT(M2);
IfM1=M2SOWrite('The two words are anagrams')
OtherwiseWrite('The two words are not anagrams')
Fsi;
END.
- Second solution:the two words are then anagrams if each character appears the same number of times
in both words.
AlgorithmAnagram;
VarM1,M2:chain;
T1,T2,I,F1,F2:integer;
X:character;
Anag:boolean;
Beginning
Write('give 2 words');
Read(M1,M2);
T1←Size(M1); T2←Size(M2); Anag
←False;
IfT1=T2
SOAnag←True; I←1;
As long asI≤T1 and Anag
DoX←M1[I] ; F1←0 ;
ForJ←1 to T1Do IfM1[J]=XSOF1←F1+1Fsi;Do; F2←0 ;
Do;
Fsi;
IfAnagSOWrite('The two words are anagrams')
OtherwiseWrite('The two words are not anagrams')
Fsi;
END.
- Third solution:each character of M1 found in M2 is replaced by a special character (eg: '*'). At the end we check
if all the characters of M2 have been replaced.
AlgorithmAnagram;
VarM1,M2:chain;
T1,T2,I,J: integer;
Anag:boolean;
Beginning
Write('give 2 words');
Read(M1,M2);
T1←Size(M1); T2←Size(M2); Anag
←False;
IfT1=T2
SOAnag←True; I←1;
As long asI≤T1 and Anag
DoJ←1; Anag←False;
Tank J≤T1 and Non Anag
Do IfM1[I]=M2[J]SOM2[J]←'*' ; Anag←TrueFsi;J←J+1 ;Do; I←I+1 ;
Do;
I←1 ;
As long asI≤T1 and Anag
Do IfM2[I]≠'*'SOAnag←FalseFsi;I←I+1 ;Do;
Fsi;
IfAnagSOWrite('The two words are anagrams')
OtherwiseWrite('The two words are not anagrams')
Fsi;
END.
EXERCISE 1
1- Define a TIME type which contains the hour, minute, second fields.
2- Write a parameterized action which performs the sum T of two durations T1 and T2 of time type.
3- Write a TRANSFORM function which transforms a time T of type TIME into an integer S which
express this time in seconds.
Example: for T = 2 hours 10 minutes 37 seconds, S = 7837 seconds.
4- Write a DECOMPOS procedure which decomposes a time S expressed in seconds into a time T of
type TIME.
Example:for S = 7837 seconds, T = 2 hours 10 minutes 37 seconds.
5- Given two times T1 and T2 of type TIME, write an algorithm which calculates the time T sum
times T1 and T2 (T, T1 and T2 are of type TIME) using the TRANSFORM and DECOMPOS
actions.
X←T1.S+T2.S;
TS←X mod 60; TM← X
←T.M+T1.M+T2.M;
TM← TH← X div 60+ T1.H+T2.H;
END;
3- FunctionTRANSFORM(T:TIME):integer;
Beginning
TRANSFORM←T.S+60*T.M+3600*TH ;
END;
In algorithms, we cannot have a record type function, so we use a procedure.
4- ProcedureDECOMPOS(I/O:integer; S/T:TIME);
Beginning
TH←S div 3600; S← S mod 3600;
TM←S div 60; TS← S mod 60;
END;
5-
AlgorithmCalculationT;
KindTIME=Recording H,M,S: integer; End; Var
T1,T2,T:TIME;
S: integer;
Beginning
DECOMPOS(S,T) ;
/*We can also do DECOMPOS(TRANSFORM(T1) + TRANSFORM(T2),T);
Write('The sum is :',TH,' :',TM,' :',TS);
END.
EXERCISE 2
A complex number Z is completely defined by its real partshasand imaginaryb(Z = a + bi). 1- Give
the declaration of a complex number,
2- Write the functions:ReelZ,ImagZAndModulegiving the attributes of a complex number
respectively: the real part, the imaginary part and the modulus),
3- Write the parameterized actions:SumZ,DiffZAndProdZnecessary for arithmetic on the
complex, respectively for addition, subtraction and multiplication, 4- Write a
procedureConjZwhich calculates the conjugate of a complex number. 5- Write a
functionEqualZwhich tests the equality of two complex numbers. 6- Write a
procedureWriteZwhich allows you to display a complex number.
Let TC be an array of N complex numbers (N<=100). Using the previous parameterized actions, write
an algorithm that:
- Displays the element ofTChaving the largest modulus. Then checks the existence of its conjugate inTC.
- Calculate the sumZsand the productZpnon-zero elements of the arrayTC.
- Calculates and displays the difference betweenZsAndZpif it is pure imaginary.
1-KindTcomplex=Record a,b:real;END; 2-
FunctionReelZ(Z:Tcomplex):real;
BeginningReelZ←Za ;END;
FunctionImagZ(Z:Tcomplex):real;
BeginningImagZ←Zb ;END;
FunctionModuleZ(Z:Tcomplex):real; Beginning
ModuleZ←Root(Za*Z.a+Zb*Zb);END;
Za←Z1.a+Z2.a ; Zb←Z1.b+Z2.b ;
END;
Beginning
6- ProcedureWriteZ(Z:Tcomplex);
Beginning
IfZb=0SOWrite(Za)
Otherwise IfZa=0SOWrite(Zb,'i')
Otherwise IfZb>0SOWrite(Za,'+',Zb,'i')
OtherwiseWrite(Za,Zb,'i')
Fsi;
Fsi;
Fsi;
END;
7-
AlgorithmComplex ;
KindTcomplex=Record a,b:real;END;
ConstZ0.a=0 ; Z0.b=0 ;/*shift of a zero complex constant; Var
TC:Array[1..100] of Tcomplex;
I,N: integer;
Z,Zs,Zp,Zm:Tcomplex;
M,Max :reel ;
Find :boolean;
/*declaration of the different APs
----
Beginning
Write('Give N');
RepeatRead(N);UntilN>0 and N≤100; /
*reading the array of complexes ForI←1
to N
DoRead(TC[I].a, TC[I].b);
/* we can also do
WithT[I]DoRead(a,b)Do;
/*or use an intermediate variable of type Tcomplex
Read(Za,Zb);
T[I]←Z;
Do;
/*Find the number with the largest modulus
Zm←TC[1] ; Max←ModuleZ(Zm);
ForI←2 to N
Do
M← ModuleZ(TC[I]) ;
IfM>MaxSO Zm← TC[I] ;
Max←M
Fsi;
Do;
Write('The complex number with the largest modulus is:',WriteZ(Zm)) ; /*
Search for the conjugate of Zm in TC Find←False; I←1; As long asI≤N and Not
Found Do
Find← EqualZ(TC[I],ConjZ(Zm)); I
←I+1 ;
Do;
IfFindSOWrite('Len conjugate exists'OtherwiseWrite('the conjugate does not exist')Fsi; /
*calculate the sum and the product, we initialize Zs to Z0 and Zp to 1 Zs←Z0 ; Zp.a←1 ; Zp.b←0 ;
ForI←1 to N
Do
IfNot EqualZ(TC[I],Z0)
SO
SumZ(Zs,TC[I],Zs) ;
ProdZ(Zp,TC[I],Zp)
Fsi;
Do;
DiffZ(Zs,Zp,Z) ;
IfReelZ(Z)=0 and ImagZ(Z)≠0SOWriteZ(Z)Fsi;
END.
EXERCISE 3
Let Tdate be a date type composed of the integer fields DD,MM,YY.
IfD1.AA>D2.AA
SOCompareD←1
Otherwise IfD1.AA<D2.AA
SOCompareD← -1
Otherwise IfD1.MM>D2.MM
SOCompareD←1
Otherwise IfD1.MM<D2.MM
SOCompareD← -1
Otherwise IfD1.JJ>D2.JJ
SOCompareD←1
Otherwise IfD1.JJ<D2.JJ
SOCompareD← -1
OtherwiseCompareD← 0
Fsi
Fsi
Fsi
Fsi
Fsi
Fsi;
END;
AlgorithmTriDate ;
KindTdate = Record DD,MM,YY: integer;END; Var
TD: Table[1..100] of Tdate;
D:Tdate;
I,J: integer;
CompareD function(D1,D2:Tdate):integer;
----
Beginning
Write('Give N');
RepeatRead(N);UntilN>0 and N≤100; /
*reading the date table ForI←1 to N
Do;
Do;
EXERCISE 4
Write a function that determines the difference in number of days between two dates.
BIS6 function(A:integer):boolean;
Beginning
If(A mod 4=0 and A mod 100≠0)or(A mod 400=0)
SOBIS6←TrueOtherwiseBIS6← False Fsi;
END;
- A NBJour function which gives the number of days from 01/01/AA to DD/MM/AA of a given date
NBjour function(D:Tdate):integer;
VarI: integer;
Beginning
NBDay←D.DD ;
ForI←1hasD.MM-1
Do
CaseIWorth
1,3,5,7,8,10,12 : NBDay←NBDay+31 ; /*monthWith31 days
4,6,9,11 : NBDay←NBDay+30 ; /*monthWith30 days
2:IfBIS6(D.AA)SONBJour←NBJour+29OtherwiseNBJour←NBJour+28Fsi;
Farms;
Do;
END;
We resume theFunctionwhich compares 2 dates.
CompareD function(D1,D2:Tdate):integer;
-----
Finally our function:
D1 D2
D1 J2
Years (in days) between the two dates (DA)
DiffDay Function(D1,D2:Tdate):integer;
VarJ1,J2: integer;
D:Tdate;
Beginning
EXERCISE 5
Let a record E be defined by two pieces of information:
- T an array of integers that can contain a maximum of 100 elements;
- N the number of elements in the array T.
Given a string M, write a parameterized action that returns a record of type E containing all the
positions of the string 'ab' in the string M.
Example: M = 'faabaababbaabrs'
Positions: 3 - 6 - 8 - 12
Number of elements: 4
KindE=Recording
T: Array[1..100] of integer; N:
integer;
END ;
ProcedureABPos(E/ M:string[250];S/ Pos:E); VarI,J,T:
integer; Beginning
EXERCISE 6
Consider the following record types: Type
TDate = Record
Day, month, year: integer;
END;
TAddress = Registration
Number: integer;
Street: string [50];
City: string [20];
Wilaya: string [20];
Cw: integer; { Wilaya Code }
END;
THabitant = Recording
Name, first name: string [20];
Date_of_birth: date;
Residence: Address;
END;
Write an algorithm to:
1- Fill in a table T of N inhabitants (N≤100).
2- Display from T the addresses of residents born before a given year of birth.
3- Display the names and dates of birth of the inhabitants of the city of 'Zemmouri' in the wilaya of
'Boumerdes'.
4- Edit the number of inhabitants per wilaya.
AlgorithmResident;
KindTDate = Recording
Day, month, year: integer;
END;
TAddress = Registration
Number: integer;
Street: string [50];
City: string [20];
Wilaya: string [20];
Cw: integer; { Wilaya Code }
END;
THabitant = Recording
Name, first name: string [20];
Date_of_birth: date;
DIfdence: Address;
END;
VarT: Table[1..100] of THabitant;
TW:Array[1..48] of integer;
I,N,A:integer;
EH:THabiant;
Beginning
Write('Give N');
RepeatRead(N);UntilN>0 and N≤100;
Do
WithT[I].Date_of birth, T[I].Residence
Do
IfYear=ASOWrite(Number,' ',Street,' ',City,' ',Wilaya)Fsi;
Do;
Do;
/*display names and addresses of residents of Zemmouri
ForI←1 to N
Do
WithT[I],T[I].Date_of birth,T[I].Residence
Do
IfCity='zemmouri' and Wilaya='Boumerdes'
SOWrite(Name,First name,' ',Day,'/',Month,'/',Year)Fsi;
Do;
Do;
/*number of inhabitants per wilaya; /
*initialize to 0;
ForI←1 to 48DoTW[I]←0 ;Do; ForI←1
to N
DoTW[T[I].ReIfdence.CW]← TW[T[I].Residence.CW]+1 ;Do;
/*we can also use an intermediate variable /* A
← T[I].Residence.CW; TW[A]← TW[A]+1;
/*display
ForI←1 to 48DoWrite('Wilaya',I,'Number',TW[I]);Do;
END.
EXERCISE 7
We are interested in the management of vehicles in a fleet. Each vehicle is characterized by a registration number,
a brand, a model, a color, the number of seats, a taxable horsepower.
- Establish the list (registration number, make, model, power) of vehicles of a given color;
- Establish a statistical table containing the number of vehicles registered by wilaya;
1-
KindTVehicule=Recording
Brand:chain[20];
Model: string[10] ;
Nbp,Then:integer;
END;
2- New structure after decomposition of the registration
number: KindTMatricule=Registration
Num:string[6];
Cat: character;
Year:chain[2];
END;
TVehicule=Recording
Registration number: TRegistration number;
Brand:chain[20];
Model,Color:string[10];
Nbp,Then:integer;
END;
3-
AlgorithmPark ;
KindTMatricule=Registration
/*declare the different fields as strings in order to be able to display the 0 /
*without doing any processing
Num:string[6];
Cat: character;
Year:chain[2];
Cw:string[2];
END ;
TVehicule=Recording
Registration number: TRegistration number;
Brand:chain[20];
Model,Color:string[10];
Nbp,Then:integer;
END ;
Var TP: Array[1..500] of Tvehicule ;
TW: Array[1..48] of integer ;
V: Vehicle;
I,N,A: integer;
Collar: chain[10] ;
/*Function to convert a string into an integer; Function
ValCh(ch:string[10]):integer; VarI,T,P,V: integer;
Beginning
Write('Give N');
RepeatRead(N);UntilN>0 and N≤500; /
*reading the Vehicles table ForI←1 to
N
Do
WithV,V.Matriculation number
Do
Read(Num,Cat,Year);
Read(Brand,Model,Color,Nbp,Then);
Do;
TP[I]←V;
Do;
Write('Give a color'); Read(Col); ForI
←1 to N
Do
WithTP[I], TP[I].Matriculation
number Do
IfCol=Color
SO
Write(Num,'-',Cat+Year,'-',Cw);
Write(Make,Model, ,Then);
Fsi;
Do;
Do;
/*number of vehicles per wilaya; /
*initialize to 0;
ForI←1 to 48DoTW[I]←0 ;Do; ForI←1
to N
DoA← ValCh(TP[I].Matricule.Cw); TW[A]← TW[A]+1;Do; /
*display
ForI←1 to 48DoWrite('Wilaya',I,'Number',TW[I]);Do;
END.
EXERCISE 1
Let the file NUMBERS.BIN contain a list of integers. Write an algorithm that displays the
numbers in the file, their sum and their average.
AlgorithmNumber;
VarF: Integer file;
X,S,Nb: integer; M: real;
Beginning
Assign(F,'NUMBERS.BIN'); Reread(F);
Nb←0; S←0;
As long asNon FDF(F)
Do
Read(F,X); /*Read an element from the
file Write(X); /*display on screen S
←S+X; Nb←Nb+1;
Do;
IfNb≠0SOM←S/Nb ;
Write('Sum of elements =',S,' Average =',M)
OtherwiseWrite('Empty file')
Fsi;
Close(F);
END.
EXERCISE 2
1- Write an algorithm that creates the file MOTS.TXT containing a series of words (maximum length of a word:
20 characters). The word entry will end when the symbol is entered'*'which will not be written to the file.
2- Write an algorithm that displays the number of words as well as the average length of the words contained in the
MOTS.TXT file.
3- Write an algorithm that creates a second MOTS10.TXT file containing the words from the MOTS.TXT file
more than 10 characters.
AlgorithmTreatWord;
VarF,G:String file[20];
X:string[20];
Nb: integer; M:reel;
Beginning
/*question 1
Assign(F,'WORDS.TXT'); Rewrite(F); /*open F in writing Write('Give a
sequence of words. Enter the word '*' to stop typing'); Read(X);/*Read
the first word outside the loop As long asX≠'*'
Do
Write(F,X);
Read(X); /*Read the next word
Do;
Close(F);
/*question 2
Nb←0 ; M←0 ;/*we can use M for the sum of the lengths then for the average
Reread(F)/*open F in reading As long asNon FDF(F)
Do
Read(F,X);/*Readan element of the
file M←M+Size(X); Nb←Nb+1; Do;
IfNb≠0 SO M←M/Nb ;
Write('Number of words =',Nb,' Average length =',M)
Otherwise Write('Empty file')
Fsi;
Close(F);
/*question 3
Assign(G,'MOTS10.TXT') ; Rewrite(G) ; Reread(F)/*open G for writing and F for reading As
long asNon FDF(F)
Do
Read(F,X);/*Readan element of the
file IfSize(X)>10SOWrite(G,X)Fsi; Do;
Close(F); Close(G);
END.
EXERCISE 3
Consider the following record type:
Student Type = Record
Registration number: integer;
Name, First name: string [20];
Average: real;
END;
EitherTa table of at most 100 students.
Write an algorithm to copy all admitted students belonging toTin a fileADMITTEDstudent type. A
student is admitted if his average is greater than or equal to 10.
AlgorithmStudy ;
KindStudent = Registration
Registration number: integer;
Name, First name: string [20];
Average: real;
END;
Var T:Table[1..100] of Student;
F:File of Student;
X: Student;
I,N: integer;
Beginning
Read(Name,First name);
Read(Average);
Do;
T[I]←X ;
/*We can use T[I] directly and avoid the assignment(in blue) With
T[I]
Do Read(Matriculation number);
EXERCISE 4
Consider the following records:
KindTDate =RegistrationDay, month, year: integer;END;
TDiscipline =RegistrationDiscipline: chain [10]; Faculty: chain [20];END;
Student =RegistrationName, first name: string [20];
DateN: TDate;
Sector: TDiscipline;
END;
EitherStudenta student file. Write an algorithm that allows:
- Fill in the fileStudent.
- Explode the fileStudentin two files,F1(students of the faculty'FEI') AndF2(students from other
faculties).
AlgorithmBurst;
KindTDate = Record Day, month, year: integer; End;
TDiscipline = Record Discipline: string [10]; Faculty: string [20]; End;
EXERCISE 5
1- Let F1 and F2 be two files of strictly positive integers without repetition. Write an algorithm that constructs
(creates) a file G of integers such that G contains for each value of F1 the value and all its multiples
belonging to F2 (F1 and F2 are assumed to exist).
Example :
F1: 3 10 20 17
F2: 3 6 19 60 40 30
G:3 3 6 60 3010 60 40 3020 60 4017
2- Write an algorithm which allows from the result file (G) to generate another file (H) containing all
the values of the file (G) (without repetition) with their number.
Example :
H: 32 61 603 302 101 402 201 171
1-
AlgorithmMultiple ;
Var F1,F2,G: integer file; X,Y:
integer;
Beginning
Close(F2);
Do;
Close(F1); Close(G);
END.
2-
AlgorithmValRepetition;
Var G,H,G1,G2: integer file;
X,Y,N :integer:Inter:boolean;
Beginning
Do
Read(G1,Y);
IfX=YSON ←N+1Otherwise Write(G2,Y)Fsi; Do
;
/*Write the repetition of X
Write(H,N);
Close(G1); Close(G2);
/*Copy G2 to G1 To process the rest. Overwrite the old G1
Reread(G2); Rewrite(G1);
As long asNon FDF(G2)DoRead(G2,X); Write(G1,X);Do;
/*or to optimize, change the assignment of the 2 files G1 and G2 in an alternating manner
Inter← No Inter ; If Inter
SO Assign(G1,'Inter1'); Assign(G2,'Inter2');
Otherwise Assign(G1,'Inter2'); Assign(G2,'Inter1');
Fsi ;
Close(G1); Close(G2);
/*Reopen G1 for reading (unprocessed)
Reread(G1);
Do;
Close(G1); Close(H);
END.
EXERCISE 6
Let F be a file of integers representing sequences of numbers separated by one or more zeros. Write an algorithm
that performs the following processing:
1- From F (existing file), create a file G containing for each sequence, the average of the numbers which
constitute it.
2- Then, Delete the null values from the G file.
Example:
F: 0 01 4 3 7 0 0 06 -9 2 7 -6 0-10 3 0 0
AlgorithmProcessFile;
VarF: Integer file;
G,H: Reel file;
X,S,Nb: integer; M: real;
Beginning
Assign(F,'FileF'); Reread(F);
Assign(G,'FileG'); Rewrite(G); As
long asNon FDF(F)
Do
Read(F,X);
IfX≠0
SOS←0 ; Nb←0 ;
As long asNo FDF(F) and X≠0
Do S←S+X ;
Nb←Nb+1 ;
Read(F,X);
Do;
/*processing the last non-zero element of the file, the head is onFDF, but X not
treated? IfX≠0SOS←S+X ; Nb←Nb+1Fsi; M←S/Nb ;
Write(G,M);
Fsi;
Do;
Close(F); Close(G);
/*To remove null values from G we use an intermediate file, then we copy this /*file
into G
Assign(H,'Inter'); Rewrite(H); Reread(G); As
long asNon FDF(G)
Do
Read(G,X);
IfX≠0SOWrite(H,X)Fsi; Do;
Close(H); Close(G);
/*copy H to G
Reread(H); Rewrite(G);
As long asNon FDF(H)
Do
Read(H,X);
Write(G,X);
Do;
Close(H); Close(G);
END.
EXERCISE 7
Let F1 be a character file containing a sequence of telegrams. Each telegram consists of a sequence of words
separated by one or more spaces (̂ ). The telegram ends with the word 'FINTEL'.
Write an algorithm that allows, for each telegram, to print the text, respecting the following
conventions:
- Printed words will be separated by a single space.
- Words cannot exceed 12 characters otherwise they will be truncated on the right.
- The text of each telegram is followed by an indication of the total number of words (truncated or not) and the number of
truncated words.
- The end of each telegram will be indicated by 'FINTEL'.
Assign(F,'telegram.txt'); Reread(F);
Nbmot←0; NbmotTq←0;
As long asNon FDF(F)
Do
Read(F,C);
IfC<>' '
SO
Word←''/*initialize empty word As
long as(No FDF(F) and C< >' ' ) Do
Word←Word+C;/*use concatenation
Read(F,C);
Do;
/*process last character IfC< >' '
SOWord←Word+CFsi; If
word='FINTEL'
SO /*end processing Write(nbmot,'
',nbmotTq,' FINTEL') ; IfNon FDF(F)
SOTo write(' ')Fsi; Nbmot←0;
NbmotTq←0;
Otherwise /*word processing
Nbmot←Nbmot+1;
IfSize(Word)>12
SO WordTq←Word;/*This action truncates the word
NbmotTq←NbmotTq+1;
Word←WordTq
Fsi;
Write(Word,' ')
Fsi
Fsi;
Do;
Close(F);
END.
AlgorithmTelegram;
VarF,FC:Character file;
Nbmot, NbmotTq,I,T: integer; C:
character;
Word:string;
WordTq:string[12];
FunctionIntToStr(X:integer):string; Var
R:integer; Ch:string; Beginning
Ch←'';
Repeat
R←X MOD 10;
X←X DIV 10;
CaseRWorth
0:Ch←'0'+Ch;
1:Ch←'1'+Ch;
2:Ch←'2'+Ch;
3:Ch←'3'+Ch;
4:Ch←'4'+Ch;
5:Ch←'5'+Ch;
6:Ch←'6'+Ch;
7:Ch←'7'+Ch;
8:Ch←'8'+Ch;
9:Ch←'9'+Ch;
Farms;
UntilX=0;
IntToStr←Ch;
END;
Beginning
Assign(F,'telegram.txt'); Reread(F);
Assign(FC,'telegramC.txt'); Rewrite(FC);
Nbword←0; NbwordTq←0;
As long asNon FDF(F)
Do
Read(F,C);
IfC<>' '
SO
Word←'' /* initialize empty word
As long as(No FDF(F) and C< >' ' )
Do
Word←Word+C; /*use concatenation
Read(F,C);
Do;
/*process last character
IfC< >' 'SOWord←Word+CFsi; If
Word='FINTEL'
SO /*end processing
Word←IntToStr(nbword)+' '+IntToStr(nbmotTq)+' FINTEL' ;
IfNon FDF(F)SOWord←Word+' 'Fsi; T←Size(Word);
ForI←1 to TDoWrite(FC,Word[I])Do;
Nbmot←0; NbmotTq←0;
Otherwise /*word processing
Nbmot←Nbmot+1;
IfSize(Word)>12
SO WordTq←Word;/*This action truncates the word
NbmotTq←NbmotTq+1;
Word←WordTq
Fsi;
Word←Word+' ' ;/*add a blank T
←Size(Word);
ForI←1 to TDoWrite(FC,Word[I])Do
Fsi
Fsi;
Do;
Close(F); Close(FC);
END.
EXERCISE 8
Write a procedure that deletes the last element of the integer file F.
Using the previous procedure, write an algorithm to empty an existing file F of integers and physical name
'ESSAI.DAT', element by element. This algorithm should display, after the deletion of each element, the
average of the remaining elements of F.
KindFent:Integer file;
/*the assignment can be done inside the procedure, but we prefer to do it outside
Assign(F,'FENT.DAT');
ProcedureSupD(E/S/F:Fent);
VarG: Fent; X, integer;
Beginning
Reread(F);
Ifnon FDF(F
SO /*the assignment of the intermediate file is done inside, because it is a local file
Assign(G,'G'); Rewrite(G); Read(F,x);
/* starting with Writing before Reading allows you to copy the elements of F /* into G
except the last one, we willRead, but we don't write it, the head is onFDF, if F /* contains
only one element. It will not be copied to G (the loop does not execute, we are on /*FDF)
Do
Read (G,x);
Write (F,x);
Do;
Close(G);
Fsi;
Close(F);
END;
AlgorithmPhone ;
VarF:integer file;
X,S,Nb: integer; M: real;
ProcedureSupD(E/S/F:Fent);
-----
Beginning
Assign(F,'ESSAI.DAT');
Reread(F);
As long as not
FDF(F) Do
SupD(F);
Reread(F);
S←0 ; Nb←0 ;
As long as not
FDF(F) Do
Read(F,X);
S←S+X ; Nb←Nb+1 ;
Do;
IfNb≠0SOM←S/Nb ;
Write('Average=',M)
OtherwiseWrite('File is empty')
Fsi;
Do;
Close(F);
END.
EXERCISE 9
Let F1 and F2 be two files of strings. Each string represents a word. Write an algorithm that constructs
a file F3, such that F3 contains the words in F1 that do not exist in F2.
AlgorithmWord123;
Var F1,F2,F3: string file[30]; X,Y:
String[30];
Find :boolean;
Beginning
Read(F2,Y);
IfY=XSOFind ←TrueFsi; Do;
Do;
Close(F1); Close(F3);
END.
EXERCISE 10
Let's say the following type:
Beginning
Assign(F,'Product.dat'); Reread(F);
Ftrie ←True;
IfNon FDF(F)
SO Read(F,Eprod);
As long asnon FDF(F) and Ftrie
Do code ←Eprod.code ;
Read(F,Eprod);
Ifcode> Eprod.codeSOFtrie ← FalseFsi;
Do
Fsi;
END;
EXERCISE 11
Using mobile phones allows storing the contact directory in two files:
- A 'TEL.DAT' file, saved in the phone's memory;
- A 'SIM.DAT' file, saved on the SIM card memory.
Each file contains references of a contact grouping: a name, a first name and a telephone number. The elements of
the two files are assumed to be already sorted according to the telephone number.
1- Give the syntax (instructions) for assigning and opening the two files.
2- Write a procedure that allows you to store duplicates in another file. An element is a duplicate if it
exists in both files.
1- Assign(Ftel,'tel.dat'); Reread(Ftel);
Assign(Fsim,'sim.dat'); Reread(Ftel);
2-
Kindcontact=Registration
Name,first name:string[30];
Number:string[10];
END ;
ProcedureFdouble(E/Ftel,Fsim:contact file; S/FD:contact file); Var
cont1,cont2:contact;
Find,double:boolean;
Beginning
Double ←true ;
As long asnon FDF(ftel)
Do Read(Ftel,cont1);
Reread(fsim); find ←false; As long as
not FDF(fsim) and not found Do
Read(fsim,cont2);
Ifcont1=cont2So ifdouble
SO Assign(FD,'Fdouble.dat');
Rewrite(FD); double ←False
Fsi;
Write(FD,cont1);
Find ←True
Fsi;
Do;
Close(fsim);
Do;
Close(Ftel);
Ifnon-doubleSOclose(FD)Fsi;
END;
EXERCISE 12
EitherFmotan alphabetic character file containing words separated by one or more whitespace characters. 1-
Write a functionPalindromewhich checks if a given word is a palindrome word.
2- Write an algorithm that displays the number of palindrome words and the shortest palindrome word.
1-
FunctionPalindrome(word:string):boolean;
Var I,T: integer;
Beginning
Do;
END;
2-
AlgorithmCourtPal;
Kindch:chain[50];
Var Fmot: character file;
tmin,t,NBpal: integer;
X: character;
Word,cpal:ch;
FunctionPalindrome(word:string):boolean;
------
Beginning
Assign(Fmot,'fmot'); reread(Fmot);
tmin ←51; cpal ←''; NBpla← 0; As long
asnon FDF(Fmot)
Do Read(Fmot,X);/*retrieve a word
Word←'' ;/*initialize empty As long
asnon FDF(Fmot) and (X<>' ' Do
Word←Word+X ;
Read(Fmot,X);
Do;
/*process last character IfX<>' '
SOWord←Word+XFsi;
IfWord<>''
SO
IfPalindrome(word)
SO t ←Size(word); NBpal←NBpal+1 ; If
t<tmin
SO tmin ←t ;
Cpal ←word ;
Fsi;
Fsi;
Fsi;
Do;
IfNBcpal<>0
SO Write('The number of palindrome words is:',NBpal
Write('the shortest palindrome word is:',cpal)
Otherwise Write('No palindrome words or file is empty')
Fsi;
Close(Fmot);
END.
EXERCISE 13
Let F be an integer file (assumed to exist) composed of sequences of numbers, each sequence is a repetition of the
same number (non-zero). All sequences are separated by a zero. And no sequence of the same number is repeated
in the file.
F 14 14 14 0 5 5 0 29 29 29 29 0 6 6 6
Position 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1- Write a parameterized actionCompresswhich creates a G record file containing for each sequence the
number represented as well as the length of the sequence.
Number 14 5296
G
Length 3 243
2- Using a single traversal of the file G and without re-traversing the file F, find the position in F of the most
long sequence. (ex:Position = 8)
3- Write a parameterized actionDecompresswhich allows to reconstruct a file H (of the same type as F) at
from a file of the same type as G.
1-
Kind
Elcp=Registration
Val,Long:integer;
END ;
Fent: Integer File;
Felcp: Elcp File;
3-
ProcedureDecompress(I/O/G:Felcp; I/O/F:Fent);
VarI:Integer; EC:Elcp;
Beginning
Reread(G); Rewrite(F); As
long asNon FDF(G)
DoRead(G,EC);
ForI ← 1 to EC.Long DoWrite(F,
EC.Val);Do; IfNon FDF(G)SO
Write(F,0)Fsi;
Do;
Close(G); Close(F);
END;
EXERCISE 1
Let A be a matrix (N,M) of integers. Write an algorithm that generates two lists from this matrix. 1- The
first one groups the minimums of the lines (FIFO);
2- And, the second the sum of the columns (LIFO).
AlgorithmMatList;
Kind Plist=^List;
List=Record
Val: integer;
Next: List;
END;
Var A: Array[1..100,1..150] of integer;
I,J,N,M,Min,S: integer;
Lmin,Lsom,P,Q:Plist;
Beginning
Do /*calculation of
Min i Min← A[I,1] ;
ForJ←2hasMDo IfA[I,J]<MinSOMin← A[I,J]Fsi;Do; /*create a
list item and update the chaining Allocate(Q);
EXERCISE 2
Let be a list of integersL, write the following parameterized actions allowing:
1- Calculating the number of elements, and determining the maximum and
minimum; 2- Inserting a given value val into a sorted list;
3- Deletion of duplicates (identical elements);
4- Creation of the mirror list of L (with then without creation of a new list); 5-
Duplication of a list at the beginning / at the end;
6- Merging two sorted lists of integers L1 and L2 into a sorted list L3;
1-
ProcedureCalList(E/ L: List; S/ Nbl, Max, Min: integer);
Beginning
Nbl←0 ;
IfL≠Nil
SO Max←L .̂Val ; Min←L .̂Val ; Nbl←1 ; L←L̂ .Next; As
long asL≠Nil
Do IfL .Val>Max
SOMax←L .̂Val
Otherwise IfL .Val<MinSOMin←L̂ .ValFsi Fsi
;
Nbl←Nbl+1 ;
L←L .̂Next ;
Do;
Fsi;
END;
2-
ProcedureInsert(E/S/ L:Plist; E/ V:integer);
VarP,Q,R:Plist;
Beginning
END;
3-
ProcedureSupDouble(E/L:Plist); Var
P,Q,R: List; Beginning
IfL≠Nil
SO
P←L ;
As long asP .̂Next≠Nil
Do Q←P .̂Next ; R←P ; As
long asQ≠Nil
Do IfQ .̂Val=P .̂Val
SO R .̂Next←Q .̂Next ;
Release(Q);
Q← R .̂Next
OtherwiseR←Q ;
Q←Q .̂Next
Fsi;
Do;
P←P .̂Next ;
Do
Fsi;
END;
4-
Creating a new mirror list (this is equivalent to creating a LIFO list from L)
ProcedureMirrorNew(E/L:Plist; S/M:Plist); VarP: List;
Beginning
M←Nil ;
As long asL≠Nil
Do Allocate(P);
P .̂Val←L .̂Val ;
P .̂Next←M ;
M←P ;
L←L .̂Next ;
Do;
END;
Create a mirror list of L without new allocations (this is equivalent to reversing the list).
ProcedureInvert(I/O/L:Plist); Var
P,Q: List; Beginning
IfL≠Nil
SO Q←L̂ .Next; L̂ .Next←Nile; As
long asQ≠Nil
DoP←Q .̂Next; Q .̂Next←L ;
L←Q ; Q←P ;
Do;
Fsi;
END;
5-
We can use a DF parameter for the duplication type (Start: 0; End: 1) to not write 2 Pro.
ProcedureDuplicateD(I/S/ L:Plist; E/DF:integer); Var
P,Q,R,T,T0: List; Beginning
IfL≠Nil
SO T←L ;/*save head L /*Create a
FIFO list from L
Allocate(P); P .̂Val←T .̂Val; Q←P;/*P is the head of the new list T0←T ;
T←T .̂Next ; As long asT≠Nil
6-
Merging 2 sorted lists into a new list Procedure
FusionNew(E/ L1,L2:Plist; S/ L:Plist); VarP,Q: List;
Beginning
IfL1≠Nil and L2
≠Nil SO/*create 1erelement of L
Allocate(L);
IfL1 .̂Val<L2 .̂ValSOL .Val←L1 .̂Val ; L1←L1 .̂Next
OtherwiseL .Val←L2 .̂Val ; L2←L2 .̂Next
Fsi;
P←L ;
/*browse the 2 lists
Tank L1≠Nil and L2≠Nil
Do Allocate(Q);
IfL1 .̂Val<L2 .̂ValSOQ .̂Val←L1 .̂Val ; L1←L1 .̂Next
OtherwiseQ .̂Val←L2 .̂Val ; L2←L2 .̂Next
Fsi;
P .̂Next←Q ;
P←Q ;
Do;
/*continue with L1 or with L2 As
long asL1≠Nil
Do Allocate(Q);
Q .̂Val←L1 .̂Val ; L1←L1 .̂Next; P .̂Next←Q ; P
←Q ;
Do;
As long asL2≠Nil
Do Allocate(Q);
Q .̂Val←L2 .̂Val ; L2←L2 .̂Next; P .̂Next←Q ; P
←Q ;
Do;
P .̂Next←Nil
Otherwise/*one of the 2 lists is empty or both are empty
L←Nil ;
IfL1≠Nil
SO /*create 1erelement of L
Allocate(L);
L̂ .Val←L1 .̂Val ; L1←L1 .̂Next ; P←L ; As
long asL1≠Nil
Do Allocate(Q);
Q .̂Val←L1 .̂Val ; L1←L1 .̂Next; P .̂Next←Q ; P
←Q ;
Do;
P .̂Next←Nil ;
Fsi;
IfL2≠Nil
SO /*create 1erelement of L
Allocate(L);
L̂ .Val←L2 .̂Val ; L2←L2 .̂Next; As P←L ;
long asL2≠Nil
Do Allocate(Q);
Q .̂Val←L2 .̂Val ; L2←L2 .̂Next; P .̂Next←Q ; P
←Q ;
Do;
P .̂Next←Nil ;
Fsi;
Fsi;
END;
IfL1≠Nil and L2
≠Nil SO/*create 1erelement of L
IfL1 .̂Val<L2 .̂ValSOL←L1 ;
L1←L1 .̂Next
OtherwiseL←L2 ;
L2←L2 .̂Next
Fsi;
P←L ;
/*traverse the 2 lists
Tanque L1≠Nil and L2≠Nil
Do IfL1 .̂Val<L2 .̂ValSOP .̂Next ←L1; P←L1;
L1←L1 .̂Next
OtherwiseP .̂Next ←L2; P←L2;
L2←L2 .̂Next
Fsi;
Do;
/*continue with L1 or with L2
IfL1≠Nil SOP .̂Next ←L1
OtherwiseP .̂Next ←L2
Fsi
Otherwise/*one of the 2 lists is empty or both are empty
IfL1≠Nil SOL←L1
OtherwiseL←L2
Fsi;
END;
EXERCISE 3
Let T be an array of 26 lists of strings. List 1 contains words starting with the letter 'A', list 2 contains
words starting with the letter 'B'…etc.
Declare T and write aFunctionallowing to check the existence of a word M in the structure.
/*get the head of the list of words starting with the same character as M L
←T[M[1]] ;
/*Search for M
Find←False;
As long asL≠Nil and Not
IfL .Word=MSOFind←TrueFsi; L
Found Do
←L̂ .Next ;
Do;
END;
EXERCISE 4
Let L be a list of positive integers. Write a procedure that splits the list L into two lists: Lp containing the
even integers and Li containing the odd integers. (Without creating new lists).
Lp←Nil ; Li←Nil ; As
long asL≠Nil
Do IfL .Val MOD 2=0 SO/*check if Lp head is created
IfLp=NilSO Lp←L ;
Pp←L
Otherwise Pp .̂Next←L ;
Pp←L
Fsi
Otherwise /*check if Li head is created
IfLi=Nil SO Li←L ;
Pi←L
Otherwise Pî .Next←L ;
Pi←L
Fsi
Fsi;
L←L̂ .Next ;
Do;
IfLp≠NilSOPp .̂Next←NilFsi; IfLi
≠NilSOPî .Next←NilFsi;
END;
EXERCISE 5
Let two lists of integers L1 and L2 be:
1- Write a function that checks if L1 and L2 are identical (contain the same elements in the same
order).
2- Write a function that checks if L1 is included in L2 (all the elements of L1 are in L2, here the order
does not count).
3- Write a function that checks if L1 and L2 are disjoint (L1 ∩ L2 = Ø).
1)
FunctionSame (L1,L2:Plist):Boolean;
Beginning
Same←True;
As long asL1≠Nil and L2≠Nil and
Idem DoIfL1^.Val≠L2^.ValSOSame←FalseFsi; L1
←L1^.Next ;
L2←L2^.Next ;
Do;
IfL1≠Nil or L2≠NilSOSame←FalseFsi;
END;
2)
FunctionIncluded(L1,L2:Plist):Boolean;
Var T: List;
Beginning
Included ←True ;
As long asL1≠Nil and
Included Included←False;
Do
T←L2 ;/*to return to each at the beginning of the list L2 As
long asL2≠Nil Not Included Do
IfL1^.Val=T̂ .ValSOIncluded←TrueFsi; T
←T̂ .Next ;
Do;
L1←L1^.Next ;
Do;
END;
3)
FunctionDisjoint(L1,L2:Plist):Boolean;
Var T: List;
Beginning
Disjoint ←True ;
As long asL1≠Nil and Disjoint
Do T←L2 ;/*to return to each at the beginning of the list L2 As
long asT≠Nil and Disjoint Do
IfL1^.Val=T̂ .ValSODisjoint ←FalseFsi; T
←T̂ .Next ;
Do;
L1←L1^.Next ;
Do;
END;
EXERCISE 6
Let two lists L1 and L2 of positive integer values:
Write a parameterized action to move (without allocation or freeing) even values from L1 to L2, and to
move odd values from L2 to L1;
ProcedureMove(I/O/L1,L2:List); Var
P,Q,T2:List;
Beginning
SO Q←L2 ; P←L2
Otherwise Q←T2 ; P←L2
As long asP .̂Next≠T2DoQ←Q̂ .Next ;Do
Fsi;
/*Optimization: Processing L2 from T2
As long asQ≠Nil
Do IfQ̂ .Val MOD 2≠0
SO IfQ=P
SO Q̂ .Next←L1 ; L1←Q ;
Q←Q̂ .Next;
L2←Q
Otherwise P .̂Next←Q̂ .Next ;
Q̂ .Next←L1 ; L1←Q ;
Q←P .̂Next
Fsi
Otherwise P←Q ;
Q←Q̂ .Next
Fsi;
Do ;
END ;
EXERCISE 7
EitherNOTESa grade file containing the result of the algorithmic module (existing file), such that the ith element of
the file contains the grade obtained by student numberi.
1-Write a parameterized actionCREATIONwhich builds, from the fileNOTES, a linked linear listL
containing all the students (for each student we keep the number and the grade obtained).
2-Write a parameterized actionDELETEallowing the removal of deferred students from list L (not
keep only admitted students).
Kind Pnote=^NoteAlgo ;
NoteAlgo=Recording
Num: integer;
Note: real ;
Next: Pnote;
END;
Fnote: Reel file;
1)
The file assignment is assumed to be outside: Assign(F,'Notes');
ProcedureCreation(E/F:Fnote; S/L:Pnote);
Var P,Q:Pnote;
X:real; I:integer;
Beginning
L←Nil ;
Reread(F);
Ifnon FDF(F)
SO /*create the head of the list
(fifo) Read(F,X); I←1;
Allocate(L);
L̂ .Num←I ; L .̂Note←X ; P←L ; /*create
the other elements of the list As long
asNon FDF(F)
Do Read(F,X); I←I+1;
Allocate(Q);
Q̂ .Num←I ; Q .̂Note←X ;
P .̂Next←Q ;
P←Q ;
Do;
P .̂Next←Nil
Fsi;
Close(F);
END;
2)
Procedure Deletion (I/O/L: Pnote);
Var P,Q:Pnote;
Beginning
IfL≠Nil
SO /*delete start
As long asL≠Nil and L̂ .Note<10
DoP←L ; L←L̂ .Next ; Release(P);Do; /*deletion elsewhere,
we must keep track of the previous one (P) P←L ; Q←L ;
IfP≠NilSOQ←P^.NextFsi; As
long asQ≠Nil
Do IfQ̂ .Note<10SO P .̂Next←Q̂ .Next ;
Q←P .̂Next
Otherwise P←Q ;
Q←Q̂ .Next
Fsi;
Do
Fsi;
END;
EXERCISE 8
Let L be a list of students. Each student is defined by their matriculation number (integer), their first and last name (string) and their
course ('ACAD', 'GTR' or 'ISIL').
2- Write a procedureBURSTwhich allows the list L to be split into two lists L1 containing the students of the
'GTR' and L2 stream containing students from the 'ISIL' stream. In the end, the original list L will contain
students from the 'ACAD' stream only.
1-
KindPEtud=^Student ;
Student=Registration
Registration number: integer;
Name,First name:chain[25];
Sector:chain[4];
Next: PEtud;
END;
East of theKindPetud
2-
ProcedureBurst(E/S/ L,L1,L2:PEtud);
Var P1,P2,LnP,Lp:PEtud;
Beginning
SO Ln←L ; Lp←L
Otherwise Lp^.Next←L ; Lp←L
Fsi
Fsi;
L←L̂ .Next ;
Do;
L←Ln ;
IfLn≠NilSOLp^.Next←NilFsi; IfL1
≠NilSOP1 .̂Next←NilFsi; IfL2≠Nil
SOP2 .̂Next←NilFsi;
END;
EXERCISE 9
A pharmacist wants to process information about his stock of
medicines by computer. You are asked to represent this
information in the form of a linked linear list where each element
contains the label of a medicine, the quantity available (number of
boxes) and the unit price.
1- Provide the data structures necessary for the representation of this stock (see diagram).
2- Write the procedureSell(Med, NbBoxes) allowing to remove,Ifpossible, 'NbBoites' of the drug 'Med'
from stock. (The medicine whose quantity reaches 0 must be removed from stock).
3- Write the procedureBuy(Med, NbBoites, Prix) allowing the pharmacist to supply his stock by
'NbBoxes' of the drug 'Med' having the unit price 'Price' DA. It is considered that a drug always takes
the new price.Ifthe medicine does not exist, it must be inserted.
4- Write the functionValStockto calculate the value of drugs in stock.
1-
KindPmedic=^Medic ;
Medic=Recording
Label: string[15] ;
Qty: integer;
Price: real ;
Next: Pmedic;
END;
2-
ProcedureSell(E/S/ M:Pmedic;E/ Med:string[15]; E/NB:integer; S/Possible:booleen);
Var P:Pmedic;
Beginning
Possible←False;
IfM≠Nil
SO P←M ; Q←M ;
/*Med search
As long asQ≠Nil and Q̂ .Libele≠MedDoP←Q ; Q←Q̂ .Next ;Do; If
Q≠Nil
SO /*we found Med, we test if the sale is possible
IfQ̂ .Qty≥NB
SO Possible←True;
Q̂ .Qte←Q̂ .Qte-NB ;
/*if qte becomes zero, we delete
IfQ̂ .Qty=0
So ifP=QSOM←P .̂Next ; Release(P)/*Casesup Head
3-
ProcedureBuy(E/S/ M:Pmedic; E/ Med:string[15]; E/ NB:integer; E/ Price:real); Var
P,Q:Pmedic; Beginning
IfM=Nil
SO Allocate(M);
M^.Libele←Med ;
M^.Qte←NB ;
M^.Price←Price;
M^.Next←Nil
Otherwise /*Med Search
P←M ; Q←M ;
/*Med search
As long asQ≠Nil and Q̂ .Libele≠MedDoP←Q ; Q←Q̂ .Next ;Do; If
Q≠Nil
SO /*Med was found, data is updated
Q̂ .Qte←Q̂ .Qte+NB ; Q̂ .Price←Price
Otherwise /*Med does not exist, we create it at the end, after the last element (P)
Allocate(Q);
Q̂ .Libele←Med ; Q̂ .Qte←NB ; Q̂ .Price←Price;
Q̂ .Next←Nil;
P .̂Next←Q
Fsi;
Fsi;
END;
4-
FunctionValStock(M:Pmedic):real;
Beginning
ValStock←0 ;
As long asM≠Nil
DoValStock←ValStock+M^.Qty*M^.Price ; M←M̂ .Next ;Do;
END;
EXERCISE 10
Let the structure below represent a list of lists of integers.
ListV=^ListV;
ListV=Record
Next: List;
NextV:PlistV;
END;
1-
FunctionSame (L1,L2:Plist):Boolean;
Beginning
Same←True;
As long asL1≠Nil and L2≠Nil and
Idem DoIfL1^.Val≠L2^.ValSOSame←FalseFsi; L1
←L1^.Next ;
L2←L2^.Next ;
Do;
IfL1≠Nil or L2≠NilSOSame←FalseFsi;
END;
2-
ProcedureDeleteH(I/O/LV:PlistV; I/O/LH:Plist); Var
T,TC:PlistV;
P: List;
Beginning
IfLV≠Nil
SO
IfLV̂ .NextH=LH
SO /*delete head after deleting list H
As long asLH≠NilDoP←LH ; LH←LH .̂Next ; Release(P);Do; T
←LV ; LV←LV̂ .NextV ; Release(T) /*search LV that contains LH T
Otherwise ←LV ; TC← T .̂Next ; As long asTC≠Nil
Do IfTC .̂NextH=LH
SO As long asLH≠NilDoP←LH ; LH←LH .̂Next ; Release(P);Do;
T̂ .NextV←TC .̂NextV ; Release(TC) T←TC ; TC← TC .̂Next
Otherwise
Fsi;
Do
Fsi;
Fsi;
END;
3-
ProcedureSuppDoubleH(I/O/LV:PlisteV);
Var L1,L2: List;
T,TC,TR:PlistV;
Beginning
T←LV ;
IfT≠Nil
SO L1←T̂ .NextH ;
TR←T ;
TC←T .̂NextV ; /*TR is the previous of TC As
long asTC≠Nil
Do L2←TC .̂NextH ;
IfSame(L1,L2)
SO /*before releasing TC in the procedure we save its Next for the rest TC
←TĈ .NextV ;
DeleteH(LV,L2)
Otherwise TR←TC ; TC←TĈ .NextV
Fsi;
Do;
T←T̂ .NextV
Fsi;
END;
EXERCISE 11
To play Am-Stram-Gram,nchildren form a circle, they choose one of them as the first, start counting
from him and decide that thekthmust leave the round, then again thekthstarting from the next one, and
so on.
Write a function that returns the sequence (as a singly linked list) of children in the order they exited
the round.
The children's circle is represented by a linked list of strings. (It may be interesting to modify this list to
make it circular!).
Deep=^Round
Round=Recording
Name: string[20] ;
Next: Deep;
END;
Output←Nil;
IfL≠Nil
SO /*transform L into a circular list
P←L ;
As long asP .̂Next≠NilDoP←P .̂Next ;Do; P̂ .Next←L ; /
*Creation of the output list in FiFo mode Output←Nil;
IfL≠Nil
SO As long asL .Next
≠L Do For I←1 to K-2DoL←L̂ .Next ;Do; P
←L .̂Next ;/*outgoing element L̂ .Next
/*detach P
←P^.Next ; IfOutput=Nil
EXERCISE 12
Let L be a list of integers.
1- Write a procedureDETACHEDwhich returns the address of the maximum of the list L and detaches it from the listwithout the
DELETE .
2- Using the procedureDETACHED, write a procedureSORTwhich sorts the list L in descending order
(without creating a new list).
1-
ProcedureDetach(I/S/ L:Plist; S/ Pmax:Plist);
Var Max: integer;
Prx,P,Q:List;
Beginning
Pmax←L ;
IfL≠Nil
SO P←L ; Max←P .̂Val ; Pmax←L ; Q
←P .̂Next;
As long asQ≠Nil
Do IfQ̂ .Val>MaxSOMax← Q̂ .Val; Pmax←Q ;Prx←PFsi; P←Q ; Q
←Q .̂Next ;
Do;
IfPmax=L
SO L←L̂ .Next
Otherwise Prx̂ .Next←Pmax^.Next
Fsi;
Fsi;
END;
2-
ProcedureSort(I/O/L:Plist);
Var T,P,Q: List;
Beginning
/*Sorting in descending order using DETACHE involves creating a FIFO list T←Nil ;
IfL≠Nil
SO /*Create the head
Detach(L,P);
T←P ;
/*create the other elements
As long asL≠Nil
Do Detach(L,Q);
P .̂Next←Q ;
P←Q ;
Do;
P .̂Next←Nil ;
L←T
Fsi;
END;
EXERCISE 13
In this exercise, we propose to develop a module allowing to manipulate sparse polynomials. A sparse
polynomial is a polynomial containing very few non-zero monomials.
Example: P(x) = 5.6 x1280+ 0.8 x – 9 contains 1281 terms of which only 3 are non-zero. Each
monomial is described by a record of typeTmonomecomprising the following 3 fields:
- Deg:integer representing the degree of the monomial;
- Coef:real representing the coefficient of the monomial;
- Next:pointer to the next monomial.
The list representing the polynomial will be sorted in descending order of degree. An empty list (Nil) corresponds to the zero
polynomial;
1- Write a procedureAddwhich adds to a polynomial (Pol) the value
of a monomial defined by its degree (Deg) and its coefficient (Coef). 2-
Write the proceduresSumAndProductwho respectively realize the
sum and product of two polynomials Pol1 and Pol2.
3- Write aValue Functionwhich calculates the value of the polynomial for a
value val of the variable x.
4- Write a procedureDerivativewhich determines the derivative DPol of a polynomial Pol.
5- Write a procedurePrimitivewhich determines the primitive PPol of a polynomial Pol, knowing that
PPol(0)=1.
Kind
Tmonome=̂ Monome ;
Monome=Recording
Coef:real;
Deg: integer;
Next: Tmonome;
END;
1-
ProcedureAdd(I/O/Pol:Tmonome; E/M:Tmonome); Var
P,Q: Tmonome; Beginning
IfM^.Coef≠0
SO
IfPol=Nil
SOPol←M ; M^.Next←Nil
Otherwise/*search for add position or update Coef in =
IfM^.Deg>Pol.Deg
SOM^.Next←Pol ; Pol←M/*add to beginning
Otherwise IfPol̂ .Deg=M^.Deg
SO /*update Coef, then free M
Pol̂ .Coef←Pol̂ .Coef+M .̂Coef ;
Free(M)/*inCaseequality, we no longer need M /*If the
Coef becomes zero, we remove the monomial
IfPol̂ .Coef=0SOP←Pol ; Pol←Pol̂ .Next ; Release(P)Fsi
OtherwiseP←Pol ; Q←P .̂Next ;
As long asQ≠Nil and
Q .̂Deg>M^.Deg DoP←Q ; Q
←Q .̂Next ;Do; IfQ=Nil
SOP .̂Next←M ; M .̂Next←Nil
Otherwise IfQ .̂Deg=M^.Deg
SOQ .̂Coef←Q .̂Coef+M .̂Coef ;
Free(M)/*inCaseequality, we no longer need M /*If the
Coef becomes zero, we remove the monomial
IfQ .̂Coef=0
SOP .̂Next←Q .̂Next ; Free(Q)Fsi
OtherwiseP .̂Next←M ; M .̂Next←Q
Fsi
Fsi
Fsi
Fsi
Fsi;
END;
2-
ProcedureSum(E/ Pol1,Pol2:Tmonome; S/ Pol3:Tmonome); VarM:
Tmonome; Beginning
/*Add all monomials from Pol1 to Pol3== Duplication of Pol1 In Pol3 Pol3
←Nil ;
As long asPol1≠Nil
Do Allocate(M); M^.Deg←Pol1 .̂Deg; M .̂Coef←Pol1 .̂Coef;
Add(Pol3,M);
Pol1←Pol1 .̂Next ;
Do;
/*Add all monomials from Pol2 to Pol3 As
long asPol2≠Nil
Pol3←Nil ;
IfPol≠Nil and Pol2
≠Nil SO
/*Multiply each monomial of Pol2 by Pol1 and add to Pol3 As
long asPol2≠Nil
Do P←Pol1 ;
As long asP≠Nil
Do Allocate(M);
M^.Deg← Pol2 .̂Deg +P .̂Deg ; M .̂Coef← Pol2^.Coef *P .̂Coef ;
Add(Pol3,M);
P←P .̂Next ;
Do;
Pol2←Pol2 .̂Next ;
Do;
END;
3-
FunctionValue(E/ Pol :Tmonome ; E/ X :real ):real ;
Var I: whole;
Px: real;
Beginning
Value←0;
As long asPol≠Nil
Do Px←1 ;
For I←1 to Pol̂ .DegDoPx←Px*X ;Do;/*power of X calculation Value
←Value+Pol̂ .Coef*Px; Pol←Pol̂ .Next;
Do;
END;
4-
ProcedureDerive(E/ Pol:Tmonome; S/ DPol:Tmonome); Var
M,P: Tmonome; Beginning
Dpol←Nil ;
IfPol≠Nil
SO /*create the first monomial of DPol
IfPol̂ .Deg≠0
SO Allocate(Dpol);
DPol̂ .Coef←Pol̂ .Coef*Pol̂ .Deg ;
DPol̂ .Deg←Pol̂ .Deg-1 ;
P←Dpol
Fsi;
Pol←Pol̂ .Next ;
/*create the other monomials of DPol
As long asPol≠Nil
Do IfPol̂ .Deg≠0
SO Allocate(M));
M^.Coef←Pol̂ .Coef*Pol̂ .Deg ;
M^.Deg←Pol̂ .Deg-1 ;
P .̂Next←M ;
P←M ;
Fsi;
Pol←Pol̂ .Next ;
Do;
IfDpol≠NilSOP .̂Next←NilFsi
Fsi;
END;
- We can also calculate the Derivative usingAdd,but the first solution is moreoptimal.
Dpol←Nil ;
As long asPol≠Nil
Do IfPol̂ .Deg≠0
SO Allocate(M));
M^.Coef←Pol̂ .Coef*Pol̂ .Deg ;
M^.Deg←Pol̂ .Deg-1 ;
Add(DPol,M);
Fsi;
Pol←Pol̂ .Next ;
Do;
END;
5-
ProcedurePrimitive(E/ Pol:Tmonome; S/ PPol:Tmonome); Var
M,P: Tmonome; Beginning
Ppol←Nil ;
IfPol≠Nil
SO /*create the first monomial of PPol
Allocate(Ppol);
PPol̂ .Coef←Pol̂ .Coef/(Pol̂ .Deg+1);
PPol̂ .Deg←Pol̂ .Deg+1 ;
P←Ppol ;
Pol←Pol̂ .Next ;
/*create the other monomials of PPol
As long asPol≠Nil
Do Allocate(M));
M^.Coef← Pol̂ .Coef/(Pol̂ .Deg+1);
M^.Deg←Pol̂ .Deg+1 ;
P .̂Next←M ;
P←M ;
Pol←Pol̂ .Next ;
Do;
Fsi;
/*create the constant
Allocate(M); M̂ .Deg←0; M̂ .̂Coef←1; M̂ .Next←Nil;/*PPol(0)=1 If
Ppol≠NilSOP .̂Next←MOtherwisePPol←MFsi;
END;
- We can also calculate the primitive usingAdd,but the first solution is moreoptimal.
Ppol←Nil ;
As long asPol≠Nil
Do Allocate(M));
M̂ .Coef← Pol̂ .Coef/(Pol̂ .Deg+1);
M̂ .Deg←Pol̂ .Deg+1 ;
Add(Ppol,M);
Pol←Pol̂ .Next ;
Do;
/*create the constant
Allocate(M); M^.Deg←0; M.̂Coef←1; M^.Next←Nil;/*PPol(0)=1 If
Ppol≠NilSOP .̂Next←MOtherwisePPol←MFsi;
END;
EXERCISE 14
Definition : A matrix is called sparse if it mainly contains
zero coefficients (elements).
03 90 0 0 0 0 0 0 0 0
0 0 0 0 0 01040 0 0
A sparse matrix can be represented by taking into account only the non-zero elements using a
linked list. Using the list representation of a sparse matrix:
1- Give the declaration of the necessary data structure.
2- Write the procedure to fill such a structure for a given sparse matrix A(M,N). 3- Write the
parameterized action to calculate the sum of two matrices thus represented.
4- Write a procedure to display a matrix represented in this way.
1-
KindPMat= Matrix ;
Matrix=recording
I,J,Val: integer;
Next:list;
END;
2-
ProcedureFillA(E/S/A:Pmat); Var
P,Q:list;
I,J,V: integer;
Beginning
A←Nil ;
Read(I,J,V);
IfV<>0
SO /*create head
Allocate(A);
 .I ←I ;  .J ←J ;  .Val ←V ; P←A;
/*create the rest of the elements, we consider that the values are introduced line by line
Read(I,J,V);
As long as V<>0
Do Allocate(Q);
Q̂ .I ←I ; Q̂ .J ←J ; Q .Val ←V ;
P .̂Next←Q;
P ←Q ;
Read(I,J,V);
Do;
P .̂Next←Nil
Fsi;
END;
3-
ProcedureSum(E/ A,B:Pmat; S/ C:Pmat);
Var P,Q,R,E:Pmat;
Beginning
/*Creating the matrix C comes down to merging the 2 lists A and B based on the indices C
←Nil ;
As long asA≠Nil and B
≠Nil Do IfHAS .I<B .̂I
SO Allocate(E);
E .̂I←Â .I ;E .̂J←A .̂J ; E .̂Val←A .̂Val ; A
←A .̂Next
Otherwise IfHAS .I>B .̂I
SO Allocate(E);
E .̂I←B .̂I ;E .̂J←B .̂J ; E .̂Val←B .̂Val ; B
←B .̂Next
Otherwise/*A .̂I=B .̂I, we move on to J
IfHAS .J<B .̂J
SO Allocate(E);
E .̂I←Â .I ;E .̂J←A .̂J ; E .̂Val←A .̂Val ; A
←A .̂Next
4-
ProcedureDisplayA(E/A:Pmat);
Beginning
As long asA≠Nil
EXERCISE 15
Let L be a list of characters constituting words (a word is a sequence of characters not containing a space)
separated by a single space character.
Write a procedure that reverses the words in list L without creating a new list.
Kind
Cliste=^Lcar ;
Lcar=Recording
because: character;
Next: List;
END ;
ProcedureInverseM(E/S/L:Cliste); Var
D,F,P,Q,B:Cliste; Beginning
D←L ;
IfL≠Nil
SO /*processing first word F
←L .̂Next ;
As long asF≠Nil and F̂ .Car≠'
' Do P←F̂ .Next;
F̂ .Next←L ;
L←F ;
F←P ;
Do;
D .̂Next←F ;
/* processing of other words
Q←F ;
As long asQ≠Nil
Do B←Q ;/*if Q≠Nil it is on a blank B
Q←Q .̂Next ; D←Q ;/*D is the first character of the word F
←Q .̂Next ;
As long asF≠Nil and F̂ .Car≠'
' Do P←F̂ .Next;
F̂ .Next←Q ;
Q←F ;
F←P ;
Do;
B .̂Next←Q ;/*Q is on the last character of the word
Q←F ;/*F is on a white or Nil
D .̂Next←Q ;
Do;
Fsi;
END;