1 / 40

Le langage Pascal

Le langage Pascal. Un langage de programmation Imp érative. Paradigme de programmation impérative. Abstraction du langage machine Des instructions, de la mémoire Création d’une machine virtuelle. Machine Pascal C …. Compilateur Interpréteur. Système d’ exploitation. Machine réelle.

aric
Download Presentation

Le langage Pascal

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 d’une 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 d’exécution • dimension et représentation binaire • VAR x : REAL • L’affectation sert à associer une valeur à un emplacement • X:=2 • 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 d’un Programme PROGRAMNomProgramme (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 SumAverage;const   NumberOfIntegers = 5;var   A, B, C, D, E : integer;   Sum : integer;   Average : real;   Grade : char;   Fail : boolean;begin    (* 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; x:real; 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); close(ficSor) end.

  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 d’un 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); racine:=0; WHILE racine*racine < nombre DO racine:=racine+0.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); racine:=0; REPEAT racine:=racine+0.01 UNTIL racine*racine > nombre; writeln('la racine de ', nombre,' vaut ',racine) END.

  11. Boucles: While, Repeat, For • FOR variable_énumérée:=valeur_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_cas1:instruction1; liste_de_cas2:instruction2; .... OTHERWISE instructionN END • CASE a*b 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 ', a+b+c, '.'); end; begin PrintIt(2, 3, 4); end.

  14. Procedures et Fonctions program classer(input,output); var a,b,c:real; function MAX(x,y:real):real; begin if x>=y then MAX:=x else MAX:=y end; begin writeln('entrez deux valeurs : '); readln(a,b); c:=max(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,d:real; PROCEDURE aff_somme(a,b:real); var c:real; begin c:=a+b; 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(c+a,d) END.

  17. Procedures et Fonctions: Recursivite program TowersofHanoi;Var   numdiscs : integer;procedure DoTowers (NumDiscs, OrigPeg, NewPeg, TempPeg : integer);begin   if NumDiscs = 1 then      writeln (OrigPeg, ' ---> ', NewPeg)   else      begin         DoTowers (NumDiscs-1, OrigPeg, TempPeg, NewPeg);         writeln (OrigPeg, ' ---> ', NewPeg);         DoTowers (NumDiscs-1, TempPeg, NewPeg, OrigPeg)      endend;begin    (* Main *)   write ('Please enter the number of discs in the tower ===> ');   readln (numdiscs);    writeln;   DoTowers (numdiscs, 1, 3, 2)end.     (* Main *)

  18. Passage par Valeur et par Reference program parametres;var   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,b:real):boolean; FORWARD; {déclaration anticipée de l'entête } procedure deux(x,y:real); var bool:boolean; begin ...... bool:=prem(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,dimanche); VAR jour:tj; nb_heures_cours:ARRAY[tj] OF integer; BEGIN nb_heures_cours[lundi] := 4; … sum := 0; FOR jour:=lundi TO vendredi DO sum = sum + nb_heures_cours[jour]; writeln(‘le nombre d’’heures est : ‘, sum); END.

  21. Chaines de Caractères program position(input,output); var ch,sch:string[255]; i,j,n,l,ls:integer; begin writeln('chaîne à tester ? '); readln(ch); writeln('sous-chaîne à trouver ?'); readln(sch); l:=length(ch);ls:=length(sch); n:=0; for i:=1 to l-ls do begin j:=1; while (j<=l)and(ch[i+j-1]=sch[j]) do j:=j+1; if j>ls then begin writeln('trouvé position ',i); n:=n+1 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(myString[0])); Write(myString[byte(myString[0])]); 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) <= 0 then Writeln('"Why" is not found.'); End.

  24. Enregistrements TYPE date = RECORD jour:1..31; mois:1..12; an:1980..1999 END; facture = RECORD reference:integer; jour:date; client:string[100]; total:real END; VAR date1,date2:date; comptes:array[1..100] of facture; fact:facture;

  25. Enregistrement Type Str25 = String[25]; 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 tpoint=^tval; tval=record valeur:integer; suivant:tpoint end; VAR prem,precedent,point:tpoint; i,n:integer; 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); precedent:=prem; for i:=2 to n do begin new(point); (* création d'une nouvelle variable *) write(i,'ième valeur ? '); readln(point^.valeur); precedent^.suivant:=point; (* mise à jour du chaînage *) precedent:=point (*se préparer pour la prochaine boucle*) end; precedent^.suivant:=NIL; (* NIL signifie "rien" *) point:=prem; (* heureusement, on se souvient du premier *) for i:=1 to n do begin writeln(point^.valeur); point:=point^.suivant (* pour la prochaine boucle *) end end.

  27. Exemples program calculatrice(input,output); var val1,val2,resultat:real; operation:char; begin writeln('première valeur ?'); readln(val1); writeln('opération (+ - * /) ? '); readln(operation) writeln('deuxième valeur ? '); readln(val2); case operation of '+':resultat:=val1+val2; '-':resultat:=val1-val2; '*':resultat:=val1*val2; '/':resultat:=val1/val2 end; writeln('résultat : ',resultat) end.

  28. Exemples program Fibonacci;var   Fibonacci1, Fibonacci2 : integer;   temp : integer;   count : integer;begin    (* Main *)   writeln (‘Les dix premiers nombres Fibonacci sont:');   count := 0;   Fibonacci1 := 0;   Fibonacci2 := 1;repeat      write (Fibonacci2:7);      temp := Fibonacci2;      Fibonacci2 := Fibonacci1 + Fibonacci2;      Fibonacci1 := Temp;      count := count + 1until count = 10;   writeln;end.     (* 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 &lt;&gt; 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 &lt;&gt; 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 MakeEmptyBinarySearchTree := nil end; function MakeSingletonBinarySearchTree (Elm: Element): BinarySearchTree; var Result: BinarySearchTree; begin New (Result); Result^.Datum := Elm; Result^.Left := MakeEmptyBinarySearchTree; Result^.Right := MakeEmptyBinarySearchTree; MakeSingletonBinarySearchTree := 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 EmptyBinarySearchTree (B) then B := MakeSingletonBinarySearchTree (Elm) else if Elm.Key < 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 < B^.Datum.Key then SearchBinarySearchTree := SearchBinarySearchTree (Sought, B^.Left, Found) else if B^.Datum.Key < Sought then SearchBinarySearchTree := SearchBinarySearchTree (Sought, B^.Right, Found) else begin SearchBinarySearchTree := True; { because Sought = B^.Datum.Key } Found := B^.Datum end end;

  38. Parcours d’un 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 d’un é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 d’un élément begin { procedure DeleteFromBinarySearchTree } if B <> nil then begin if Sought < B^.Datum.Key then DeleteFromBinarySearchTree (Sought, B^.Left) else if B^.Datum.Key < 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;

More Related