Le langage Pascal - PowerPoint PPT Presentation

About This Presentation
Title:

Le langage Pascal

Description:

Title: Paradigmes de Programmation Author: Robert Laganiere Last modified by: Robert Created Date: 3/7/2001 11:05:21 AM Document presentation format – PowerPoint PPT presentation

Number of Views:81
Avg rating:3.0/5.0
Slides: 41
Provided by: RobertLa49
Category:
Tags: langage | pascal

less

Transcript and Presenter's Notes

Title: Le langage Pascal


1
Le langage Pascal
  • Un langage de programmation Impérative

2
Paradigme de programmation impérative
  • Abstraction du langage machine
  • Des instructions, de la mémoire
  • Création dune machine virtuelle

Machine Pascal C
Compilateur Interpréteur
Système d exploitation
Machine réelle
3
Principe de base
  • Les variables
  • Un nom est associé à un emplacement qui contient
    une valeur
  • À la compilation, au chargement ou en cours
    dexécution
  • dimension et représentation binaire
  • VAR x REAL
  • Laffectation sert à associer une valeur à un
    emplacement
  • X2
  • l-valeur versus r-valeur

4
Programmation structurée
  • But fournir des structures de contrôle
    facilitant le raisonnment
  • Composition
  • blocs, fonctions
  • Sélections
  • if then else, switch case
  • Itérations
  • do while, for

5
Un Premier Petit Programme
  • Un programme PASCAL est composé d'une entête, des
    déclarations et des instructions (délimitées par
    BEGIN et END. ).
  • PROGRAM cercle (input,output) ( entête )
  • VAR perimetre,diametre REAL ( déclarations
    )
  • BEGIN
  • readln(diametre) ( instruction )
  • perimetre 3.141592 diametre (
    instruction )
  • writeln(diametre,perimetre) ( instruction )
  • END.

6
Structure dun Programme
  • PROGRAM NomProgramme (ListeFichiers)CONST 
    ( declarations de constantes )TYPE  (
    declarations de types )VAR  ( declarations
    de variables ) ( definitions de
    sous-programmes )BEGIN  ( instructions
    executables )END.

7
Constantes, Variables et Assignation
  • program SumAverageconst   NumberOfIntegers
    5var   A, B, C, D, E integer   Sum
    integer   Average real   Grade char  
    Fail booleanbegin    ( Main )   A 45 
    B 7   C 68 D 2   E 34   Sum
    A B C D E   Average Sum /
    NumberOfIntegers   writeln ('Nombre d''entiers
    ', NumberOfIntegers)   writeln ('Nombre 1
    ', A)   writeln ('Nombre 2 ', B)   writeln
    ('Nombre 3 ', C)   writeln ('Nombre 4 ',
    D)   writeln ('Nombre 5 ', E)   writeln
    ('Sum ', Sum)   writeln (Moyenne ',
    Average)end.     ( Main )

8
Entrees / Sorties
  • Standard read, readln lecture du clavier
  • write, writeln affichage sur écran
  • Fichiers
  • program recopier(input,output)
  • var
  • fic_ent,fic_sor file of real
  • xreal
  • begin
  • assign(ficEnt,'fichier1') ( non standard
    )
  • reset(ficEnt)
  • assign(ficSor,'fichier2')
  • rewrite(ficSor)
  • while not eof(ficEnt) do
  • begin
  • read(ficEnt,x)
  • write(ficSor,x)
  • end
  • close(ficEnt)

9
Fonctions Standards
  • Les principales fonctions standard connues par
    tous les compilateurs sont
  • ABS renvoie la valeur absolue SIN sinus
  • SQR renvoie le carré ARCTAN arc tangente
  • SQRT racine carrée EXP exponentielle
  • COS cosinus LN log népérien
  • SUCC variable énumérée suivante PRED
    précédent
  • CHR renvoie le caractere dun code ASCII ORD
    renvoie le code ASCII
  • ROUND arrondi à l'entier le plus proche
  • TRUNC partie entière (permet de mettre un réel
    dans un entier
  • trunc(4.5)4)

10
Boucles While, Repeat, For
  • PROGRAM racine_a_deux_decimales(input,output)
  • VAR nombre, racine REAL
  • BEGIN
  • writeln('entrez un réel entre 0 et 10')
  • readln(nombre)
  • racine0
  • WHILE racineracine lt nombre DO
    racineracine0.01
  • writeln('la racine de ',nombre,' vaut
    ',racine)
  • END.
  • PROGRAM racine_a_deux_decimales2(input,output)
  • VAR nombre, racine REAL
  • BEGIN
  • writeln('entrez un réel entre 0 et 10')
  • readln(nombre)
  • racine0
  • REPEAT
  • racineracine0.01
  • UNTIL racineracine gt nombre

11
Boucles While, Repeat, For
  • FOR variable_énuméréevaleur_début TO valeur_fin
    DO instruction
  • La variable_énumérée (non réelle) prend la
    valeur_début, et l'instruction est exécutée. Puis
    elle est incrémentée (on passe à la suivante,
    c.a.d si elle est entière on ajoute 1), et ce
    jusqu'à valeur_fin (compris).
  • On peut utiliser un pas dégressif en remplaçant
    TO par DOWNTO.
  • ex for lettre'Z' downto 'A' do
    writeln(lettre)
  • écrit l'alphabet à l'envers (en déclarant LETTRE
    du type CHAR)

12
IF-THEN-ELSE, CASE - OF
  • structure IF condition THEN instruction1 (CAS
    1)
  • ou IF condition THEN instruction1 ELSE
    instruction2 (CAS 2)
  • IF cond1 then if cond2 then inst1 (cond1 et
    cond2)
  • else inst2 (cond1 et pas
    cond2)
  • else if cond3 then inst3 (pas cond1
    mais cond3)
  • else inst4 (ni cond1
    ni cond3)
  • structure CASE expression OF
  • liste_de_cas1instruction1
  • liste_de_cas2instruction2
  • ....
  • OTHERWISE instructionN
  • END
  • CASE ab OF ( avec a et b déclarés entiers )
  • 0 writeln('un des nombres est nul')
  • 1,10,100,1000,
  • 10000 writeln('le produit est une puissance
    de 10')
  • otherwise writeln('autre produit')
  • END

13
Procedures et Fonctions
program AddEmUp procedure PrintIt( a, b, c
integer ) begin Writeln('The sum of a, b, and
c is ', abc, '.') end begin PrintIt(2,
3, 4) end.
14
Procedures et Fonctions
  • program classer(input,output)
  • var
  • a,b,creal
  • function MAX(x,yreal)real
  • begin
  • if xgty then MAXx else MAXy
  • end
  • begin
  • writeln('entrez deux valeurs ')
  • readln(a,b)
  • cmax(a,b)
  • writeln('le plus grand est ',c)
  • end.

15
Procedures et Fonctions Portee
  • Tous peuvent voir les variables globales A, B, et
    C.
  • Dans la procédure Alpha la définition globale de
    A est remplacée par la définition locale.
  • Beta1 et Beta2 peuvent voir les variables VCR,
    Betamax, et cassette.
  • Beta1 ne peut voir la variable FailureToo, et
    Beta2 ne peut voir Failure.
  • Aucun sous-programme sauf Alpha peut accéder F et
    G.
  • La procédure Beta1 peut appeler Alpha et Beta.
  • La fonction Beta2 peut appeler tous les
    sous-programmes, incluant lui-même (mais pas le
    programme principal)

16
Procedures et Fonctions Portee
PROGRAM portee (input,output) VAR
a,b,c,dreal PROCEDURE aff_somme(a,breal)
var creal begin cab
writeln(a ,' ', b ,' ', c) end BEGIN
programme principal writeln('entrez 4
valeurs ') readln(a,b,c,d)
aff_somme(a,b) aff_somme(3,5)
aff_somme(ca,d) END.
17
Procedures et Fonctions Recursivite
program TowersofHanoiVar   numdiscs
integerprocedure DoTowers (NumDiscs, OrigPeg,
NewPeg, TempPeg integer)begin   if NumDiscs
1 then      writeln (OrigPeg, ' ---gt ',
NewPeg)   else      begin         DoTowers
(NumDiscs-1, OrigPeg, TempPeg, NewPeg)        
writeln (OrigPeg, ' ---gt ', NewPeg)        
DoTowers (NumDiscs-1, TempPeg, NewPeg,
OrigPeg)      endendbegin    ( Main )  
write ('Please enter the number of discs in the
tower gt ')   readln (numdiscs)   
writeln   DoTowers (numdiscs, 1, 3, 2)end.    
( Main )
18
Passage par Valeur et par Reference
program parametresvar   alpha, gamma, delta
integer procedure Name (a, b integer VAR
c, d integer) begin   a 10  c
20 end begin  alpha 1  gamma
50  delta 30  Name (alpha, 2, gamma,
delta) writeln ('alpha ', alpha, 'gamma ',
gamma, 'delta ', delta)end.
19
Declaration Anticipee Forward
Une procédure devant toujours être déclarée pour
pouvoir être utilisée, on utilise FORWARD pour
les cas de récursivité passant par 2 procédures
function prem(a,breal)boolean FORWARD
déclaration anticipée de l'entête procedure
deux(x,yreal) var boolboolean begin
...... boolprem(x,y) on peut utiliser
PREM car déjà déclarée ...... end
function prem ne plus donner les arguments car
déjà déclarés begin ...... if pas_fini
then deux(a,b) ( DEUX déjà déclarée)
...... end
20
Structures de Donnees
PROGRAM heures(input,output) TYPE
tj(lundi,mardi,mercredi,jeudi,vendredi,samedi,dim
anche) VAR jourtj nb_heures_coursARRAYt
j OF integer BEGIN nb_heures_courslundi
4 sum 0 FOR jourlundi TO
vendredi DO sum sum nb_heures_coursjour
writeln(le nombre dheures est , sum) END.
21
Chaines de Caractères
program position(input,output) var
ch,schstring255 i,j,n,l,lsinteger begin
writeln('chaîne à tester ? ') readln(ch)
writeln('sous-chaîne à trouver ?') readln(sch)
llength(ch)lslength(sch) n0 for
i1 to l-ls do begin j1 while
(jltl)and(chij-1schj) do jj1
if jgtls then begin writeln('trouvé
position ',i) nn1 end end
writeln(n,' fois ',sch,' dans ',ch) end.
22
Chaines de Caractères
Var myString String Begin myString
'Hey! How are you?' Writeln('The length of
the string is ',byte(myString0))
Write(myStringbyte(myString0)) Write(' is
the last character.') End.
23
Chaines de Caractères
Var S String Begin S 'Hey there! How
are you?' Write('The word "How" is found at
char index ') Writeln(Pos('How',S)) If
Pos('Why',S) lt 0 then Writeln('"Why" is not
found.') End.
24
Enregistrements
TYPE date RECORD jour1..31
mois1..12
an1980..1999 END facture
RECORD referenceinteger
jourdate
clientstring100
totalreal END VAR
date1,date2date comptesarray1..100 of
facture factfacture
25
Enregistrement
Type Str25 String25 TBookRec
Record Title, Author, ISBN Str25
Price Real End Var
myBookRec TBookRec Begin
myBookRec.Title 'Some Book'
myBookRec.Author 'Victor John Saliba'
myBookRec.ISBN '0-12-345678-9'
myBookRec.Price 25.5 Writeln('Here are
the book details') Writeln
Writeln('Title ', myBookRec.Title)
Writeln('Author ', myBookRec.Author)
Writeln('ISBN ', myBookRec.ISBN)
Writeln('Price ', myBookRec.Price) Readln
End.
26
Pointeurs
program liste(input,output) TYPE
tpointtval tvalrecord
valeurinteger suivanttpoint
end VAR prem,precedent,pointtpoint
i,ninteger begin write('combien
d''éléments comporte votre liste ?')
readln(n) new(prem) ( le 1er est
particulier tete de liste ) write('1ère
valeur ? ') readln(prem.valeur)
precedentprem for i2 to n do begin
new(point) ( création d'une nouvelle
variable ) write(i,'ième valeur ? ')
readln(point.valeur) precedent.suivantp
oint ( mise à jour du chaînage )
precedentpoint (se préparer pour la
prochaine boucle) end
precedent.suivantNIL ( NIL signifie "rien"
) pointprem ( heureusement, on se
souvient du premier ) for i1 to n do
begin writeln(point.valeur)
pointpoint.suivant ( pour la prochaine boucle
) end end.
27
Exemples
program calculatrice(input,output) var
val1,val2,resultatreal operationchar begin
writeln('première valeur ?') readln(val1)
writeln('opération ( - /) ? ')
readln(operation) writeln('deuxième valeur ?
') readln(val2) case operation of
''resultatval1val2 '-'resultatval1-va
l2 ''resultatval1val2
'/'resultatval1/val2 end
writeln('résultat ',resultat) end.
28
Exemples
program Fibonaccivar   Fibonacci1, Fibonacci2
integer   temp integer   count
integerbegin    ( Main )   writeln (Les
dix premiers nombres Fibonacci sont')   count
0   Fibonacci1 0   Fibonacci2 1  
repeat      write (Fibonacci27)      temp
Fibonacci2      Fibonacci2 Fibonacci1
Fibonacci2      Fibonacci1 Temp      count
count 1   until count 10  
writelnend.     ( Main )
29
Les listes
type infoType integer list listNode
listNode record info
infoType next list end var l
list i infoType
30
Insertion dans les listes (solution récursive)
procedure insert(var l list i infoType) var
k list begin if (l nil) or (l.info gt
i) then begin new(k) k.info i
k.next l l k end else
insert(l.next, i) end insert
31
Insertion dans les listes (solution récursive)
else begin j l h l.next
while (h ltgt nil) and
(h.info lt i) do begin j h
h h.next end j.next k
k.next h end end insertI
procedure insertI(var l list i infoType) var
k, j, h list begin new(k) k.info i
if (l nil) or (l.info gt i) then begin
k.next l l k end
32
Afficher une liste
procedure printList(l list width
integer) begin if l ltgt nil then begin
write(l.info width) printList(l.next,
width) end else writeln end printList
33
Les listes
begin l nil insert(l, 20) insert(l,
5) insert(l, 30) insert(l, 10) insert(l,
8) insert(l, 30) insert(l, 25)
printList(l, 3) printListI(l, 4)
l nil writeln('Enter integers, ending with
0 ') repeat read(i) insertI(l, i)
until i 0 printList(l, 5) end.
34
Arbres binaires
type Element record Key
KeyType end BinarySearchTree
Component Component record
Datum Element Left, Right
BinarySearchTree end
35
Construire un arbre
function MakeEmptyBinarySearchTree
BinarySearchTree begin MakeEmptyBinarySearchTre
e nil end function MakeSingletonBinarySearchT
ree (Elm Element) BinarySearchTree var
Result BinarySearchTree begin New (Result)
Result.Datum Elm Result.Left
MakeEmptyBinarySearchTree Result.Right
MakeEmptyBinarySearchTree MakeSingletonBinarySe
archTree Result end
function EmptyBinarySearchTree (B
BinarySearchTree) Boolean begin
EmptyBinarySearchTree (B nil) end
36
Insertion dans un arbre
procedure InsertIntoBinarySearchTree
(Elm Element var B
BinarySearchTree) begin if EmptyBinarySearchTre
e (B) then B MakeSingletonBinarySearchTree
(Elm) else if Elm.Key lt B.Datum.Key then
InsertIntoBinarySearchTree (Elm, B.Left) else
InsertIntoBinarySearchTree (Elm,
B.Right) end
37
Recherche dans un arbre
function SearchBinarySearchTree (Sought KeyType
B BinarySearchTree var Found Element)
Boolean begin if EmptyBinarySearchTree (B)
then SearchBinarySearchTree False else
if Sought lt B.Datum.Key then
SearchBinarySearchTree SearchBinarySearchTree
(Sought, B.Left, Found) else if B.Datum.Key lt
Sought then SearchBinarySearchTree
SearchBinarySearchTree (Sought, B.Right, Found)
else begin SearchBinarySearchTree True
because Sought B.Datum.Key Found
B.Datum end end
38
Parcours dun arbre
procedure PrintBinarySearchTreeData (B
BinarySearchTree) begin if not
EmptyBinarySearchTree (B) then begin
PrintBinarySearchTreeData (B.Left) writeln
(B.Datum.Key) PrintBinarySearchTreeData
(B.Right) end end
39
Retrait dun élément
procedure DeleteFromBinarySearchTree (Sought
KeyType var B BinarySearchTree) var
Delend BinarySearchTree a spare pointer
to the component to be recycled function
DeleteLargest (var Site BinarySearchTree)
Element var Delend BinarySearchTree
a spare pointer to the Component to be
recycled begin if EmptyBinarySearchTree
(Site.Right) then begin DeleteLargest
Site.Datum Delend Site Site
Site.Left Dispose (Delend) end
else DeleteLargest DeleteLargest
(Site.Right) end
40
Retrait dun élément
begin procedure DeleteFromBinarySearchTree
if B ltgt nil then begin if Sought lt
B.Datum.Key then DeleteFromBinarySearchTree
(Sought, B.Left) else if B.Datum.Key lt
Sought then DeleteFromBinarySearchTree
(Sought, B.Right) else begin we've found
the datum to be deleted if
EmptyBinarySearchTree (B.Left) then begin
Delend B B B.Right
Dispose (Delend) end
else if EmptyBinarySearchTree (B.Right) then
begin Delend B B B.Left
Dispose (Delend) end else
B.Datum DeleteLargest (B.Left) end
end end
Write a Comment
User Comments (0)
About PowerShow.com