algorithme et structure de données iup1 miage. objectifs acquérir les notions de base de...

Post on 03-Apr-2015

114 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Algorithme et structure de données

IUP1 Miage

Objectifs

Acquérir les notions de base de programmation impérative

– structures de contrôles– appels à des procédures– récursivité

Connaître les bases de la programmation objet

Savoir réutiliser du code

Combien ? Quand ?

Cours/TD– 3h par semaine pendant 13 semaines le lundi de

9h à 12h

TP sur machine– 3h de TP par semaine pendant 13 semaines le

lundi de 13h30 à 16h30

Objectifs

Connaître les structures de données élémentaires, tableaux, piles, files, listes chaînées, arbres

Être sensibilisé aux problèmes algorithmiques et leur complexité

Connaître quelques algorithmes de base (tris, techniques "diviser pour régner", ...)

Le langage !

JAVA, mais son aspect orienté objet sera réduit au minimum

Il ne s'agit pas d'un cours de programmation Java !

Cours/TD– Alternance cours et exercices d'application– sur papier

TP sur machine– approfondir les structures de données et algorithmes du

cours– faire "tourner" les exercices de TD

Pointeurs …

Ce cours est largement inspiré par :– Algorithmique et Programmation en tronc commun du DEUG

– cours ASD en IUP1 de Jean-Marc Fédou

Tutorial en ligne de Sun

Documentation API

http://deptinfo.unice.fr/~pc

pc@unice.fr

Premiers pas en Java

Type de base

Variable

Méthode

Structure de contrôle

Chaîne de caractères

Type de base

Tous les langages de programmation manipulent des variables auxquelles sont affectées des valeurs

La notion de type permet de– définir les valeurs possibles– définir les opérations licites

Type de base

Type de base

byte : entier relatif (Z)

Arithmétique complément à deux sur un octet (8 bits)

[-128 , +127]

short : entier relatif (Z)

Arithmétique complément à deux sur deux octets (16 bits)

[-65536 , +65535]

Type de base

int : entier relatif (Z)

[-2147483648, 2147483647]

float : nombre réelen virgule Flottante IEEE-754

Soit à coder le nombre +3,25 (+11,01 en base 2) Normaliser l'écriture en base 2 sous la forme

(1,…).2n

+11,01 = +(1,101).21

La représentation IEEE code séparément sur 32 bits• signe (ici +) • exposant n (ici 1)• mantisse (suite de bits après la virgule, ici 101)

float : nombre réel (norme IEEE-754)

Normalisation en base 2 sous la forme :(1,…).2n

• signe sur le bit de poids fort (0 pour +)• exposant codé sur 8 bits. En fait, on code sur un octet la

valeur n+127 • mantisse codée sur les 23 bits de poids faibles

float : nombre réel (norme IEEE-754)

exposant : coder sur un octet n+12700000000 n+127 11111111

0 n+127 255 Exposants interdits

• 00000000 signifie que le nombre est dénormalisé • 11111111 indique que l'on n'a pas affaire à un nombre

Not a Number (NaN) signale des erreurs de calculs, par exemple une division par 0

1 n+127 254• Le plus petit exposant 126• le plus grand exposant +127

Norme IEEE-754http://babbage.cs.qc.edu/courses/cs341/IEEE-754.html

Programme en langage C qui affiche le code d'un nombre flottant

/* Affichage hexadécimal des 4 octets d'un nombre flottant IEEE */ #include <stdio.h>

main(){float x; unsigned char *p = (unsigned char *)&x ; printf("Entrer un nombre flottant : \n"); scanf("%f", &x); printf("%x %x %x %x\n",*p,*(p+1),*(p+2),*(p+3));

}

Type de base

double : nombre décimaux

[4.9*10-324, 1.8*10308]

char : le type caractère

Pas de méthode pour stocker directement les caractères

Chaque caractère possède donc son équivalent en code numérique

Le code Unicode (1991)

code des caractères sur 16 bits

Indépendant du système d'exploitation ou du langage

Quasi-totalité des alphabets existants (arabe, arménien, cyrillique, grec, hébreu, latin, ...)

Compatible avec le code ASCII

http://www.unicode.org

Le code ASCII (1960)

code ASCII– American Standard Code for Information

Interchange

Le code ASCII de base représente les caractères sur 7 bits (c'est-à-dire 128 caractères possibles, de 0 à 127)

Le code ASCII

Les codes 0 à 31 ne des caractères de contrôle– retour à la ligne (CR) – Bip sonore (BEL)

Les codes 65 à 90 représentent les majuscules

Les codes 97 à 122 représentent les minuscules– modifier le 6ème bit pour passer de majuscules à

minuscules– ajouter 32 au code ASCII en base décimale

Type de base

boolean : deux valeurs possibles – true (VRAI)– false (FAUX)

S’il y a du soleil ALORS je vais a la plage

SI (soleil==VRAI) ALORS aller_a_la_plage SI soleil ALORS

aller_a_la_plage

Type de base

Keyword Description Size/Format(integers)

byte Byte-length integer 8-bit two's complementshort Short integer 16-bit two's complementint Integer 32-bit two's complementlong Long integer 64-bit two's complement

(real numbers)float Single-precision floating point 32-bit IEEE 754double Double-precision floating

point 64-bit IEEE 754(other types)

char A single character16-bit Unicode characterboolean A boolean value true or false

Types de base

byte 8bits -128 to 127

short 16bits -32768 to 32767

int 32bits -2^31 to 2^31-1

long 64 bits -2^63 to 2^63-1

Integer

float 32bits 1.4E-45 3.4E38

double 64bits 4.9E-324 1.8E308

Floating

char 16bits 0 to 65535

Textual

one bit : true or false

Logical

Primitive Data Types

Concept de Variable

Définition : un élément d’information identifié par un nom

On doit explicitement indiquer le nom et le type d’une variable

On utilise le nom pour faire référence à l’information que la variable contient

Le type détermine les valeurs licites pour la variable et les opérations autorisées

Concept de Variable

Pour donner un nom et un type à une variable il faut la déclarer

type name

Une variable a une portée la section de code ou le nom de la variable peut

être utilisé

Variable : déclaration

int compteur ;

float prixHt ;

char aChar ;

boolean fin ;

Variable : valeur par défaut

Variable : affectation d’une valeur

Une affectation permet de donner une nouvelle valeur à une variable

La valeur précédente est PERDUE

int compteur ;

compteur = 3 ;

Variable : affectation d’un valeur

int r = 2 ;double pi ; pi = 3.14 ; double perimetre = 2*pi*r ;//déclarer ET affecter

char c = ’c’ ; boolean pair = true; int compteur ;compteur = compteur +1 ;

int maxInteger = Integer.MAX_VALUE;float maxFloat = Float.MAX_VALUE;char aChar = 'S';boolean fin = true;

S.o.p("Le plus grand integer est :" + maxInteger);S.o.p("Le plus grand float est :" + maxFloat);S.o.p("Le caractère est :" + aChar); S.o.p("fin est :" + fin);

Le plus grand integer est : 2 147 483 647Le plus grand float est : 3.40282e+38Le caractère est : Sfin est : true

Affectation et Conversion de type

Attention, contrairement à C, Java n'autorise pas conversions de types, sauf s'il n'y a aucune perte de précision

un entier peut être promu en double

un double ne peut pas être promu en entier

Affectation et Conversion de type

Un entier peut être promu en doubleint i = 2 ;

double d = 3.1 ;d = i ;

Un double ne peut pas être promu en entierint i = 2 ;

double d = 3.1 ;i = d ; // !!

Affectation et Cast

Un double ne peut pas être promu en entierint i = 2 ;

double d = 3.1 ;i = d ; // !!

Un double peut être forcé en entierint i = 2 ;

double d = 3.1 ;i = (int) d ;

Variable final

La valeur d’une variable déclarée final ne peut pas être modifiée après avoir été initialisée

Une telle variable est similaire à une constante dans les autres langages de programmation

Pour déclarer une variable final :

final int A_FINAL_VAR = 10;

Opérateur Arithmétique

Operator Use Description

+ op1 + op2 Adds op1 and op2

- op1 - op2 Subtracts op2 from op1

* op1 * op2 Multiplies op1 by op2

/ op1 / op2 Divides op1 by op2

% op1%op2 Computes the remainder of dividing op1 by op2

Opérateur Arithmétique

Le résultat peut dépendre du contexte

25 / 3 -----> 8//pour la division entière de 25 par 8 25.0 / 3 -----> 8.333333333333333425 / 3.0 -----> 8.3333333333333334

25 % 3 -----> 1//pour le reste de la division de 25 par 8 25 % 3.1 -----> 0.1999999999999993// 25=3.1*8 + 0.2

Opérateur Relationnel

Operateur Use Returns true if

> op1 > op2 op1 is greater than op2

>= op1 >= op2

op1 is greater than or equal to op2

< op1 < op2 op1 is less than op2

<= op1 <= op2

op1 is less than or equal to op2

== op1 == op2

op1 and op2 are equal

!= op1 != op2

op1 and op2 are not equal

Opérateur Conditionnel

Operator Use Returns true if

&& op1 && op2 op1 and op2 are both trueconditionally evaluates op2

|| op1 || op2 either op1 or op2 is trueconditionally evaluates op2

! ! op op is false

& op1 & op2 op1 and op2 are both truealways evaluates op1 and op2

| op1 | op2 either op1 or op2 is truealways evaluates op1 and op2

^ op1 ^ op2 if op1 and op2 are different

that is if one or the other of the operands is true but not both

Créer votre première application

 Le premier programme, Hello, affiche simplement le texte "Hello !" 

1. Créer un fichier source Hello.java

Un fichier source contient du texte, écrit en Java

 

2. Compiler le source en fichier bytecode Hello.class

Le compilateur javac, traduit le texte source en instructions compréhensibles par la Machine Virtuelle Java (JVM)

 

3. Exécuter le programme contenu dans le fichier bytecode

L'interprète java implémente la JVM

L'interprète traduit le bytecode en instructions exécutables par votre machine

Write once, run anywhere

La compilation d'un programme, ne génère pas d'instructions spécifiques à votre plate-forme

Mais du bytecode Java, qui sont des instructions de la Machine Virtuelle Java (JVM)

Si votre plate-forme (Windows, UNIX, MacOS, un browser Internet) dispose d’une JVM, elle peut comprendre le bytecode

Créer le fichier source Java Hello.java

class Hello {

public static void main(String[] args) {

System.out.println("Hello !");

}

}

Compiler le fichier source

> javac Hello.java

Si la compilation réussit

– le fichier Hello.class est créer

– Ce fichier contient le bytecode

Interpréter et Exécuter l'application

> java Hello

L'argument de l'interprète est– le nom de la classe à exécuter– ce n’est pas le nom du fichier

Faire la distinction M/m

Disséquons l'application "Hello"

Définir une classe

Définir la méthode main

Utiliser des méthodes

Définir la classe Hello

public class Hello {public static void main(String[] args) {

System.out.println("Hello !");

}

}

Définir la méthode main

public class Hello {

public static void main(String[] args) {

System.out.println("Hello !");

}

}

Une application Java doit contenir une méthode main– Appelée en premier par l'interprète– main appelle les autres méthodes nécessaires pour exécuter

l'application

Utiliser d’autres méthodes …

public class Hello {

public static void main(String[] args) {

System.out.println("Hello !"); }

}

> Java Hello toto titi

public class Hello {

public static void main(String [] args) {

S.o.p("Salut: ");

S.o.p(args[0]+" "+ args[1]);

}

}

Conversion String2int

Méthode int parseInt(String) de la classe Integer

public static int parseInt(String s) throws NumberFormatException – Parses the string argument as a signed decimal integer. The

characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002d') to indicate a negative value. The resulting integer value is returned

– Parameters: s - a string.

– Returns: the integer represented by the argument in decimal.

int année = Integer.parseInt("2004")

> java Somme 10 11

public class Somme {

public static void main(String args[]) {

int a = Integer.parseInt(args[0]);

int b = Integer.parseInt(args[1]); S.o.p(a+"+"+b+"="+(a+b));

}

}

Entrées au clavier

Problème : les entrées au clavier ne sont pas aisées en Java

Nous allons utilisé (Travaux Dirigés) la classe Console pour simplifier la tâche

Console.readInt(str)retourne un nombre entier de type int entré au clavier

Console.readDouble(str)retourne un nombre de type double entré au clavier

Entrées au clavier

Console.readInt(str)retourne un nombre de type intConsole.readLong(str)

retourne un nombre de type longConsole.readDouble(str)

retourne un nombre de type doubleConsole.readChar(str)

retourne un caractère de type charConsole.readLine(str)

retourne une chaîne de type String

Utiliser la classe Console

Pour chaque classe qui fait appel à la classe Console ajoutez (entre votre commentaire de début et le mot class)

import unsa.Console;

ajouter comme dernière instruction de la méthode main()

System.exit(0);

Classe Console Exemple

import unsa.Console;

public class TestConsole{

public static void main (String args[]){ char c = Console.readChar("Entrez un char");

S.o.p("echo: " + c ); int i = Console.readInt("Entrez un int"); S.o.p("echo: " + i );

System.exit(0);}

}

Générer un nombre aléatoire

Utiliser la méthode random() de la classe Math

public static double random() Returns a double value with a positive sign, greater

than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range

Math.random()

Comment obtenir un entier dans [0,n] ?

int tirage = Math.random();Types incompatibles

int tirage = (int) Math.random();retourne 0

int tirage = (int) Math.random()*100; retourne 0

int tirage = (int) (Math.random()*100);

Générer un nombre aléatoire

Utiliser la méthode nextInt(int) de la classe Random

int nextInt(int n) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence

Générer une suite aléatoire …

Random suiteAlea = new Random();

System.out.println(suiteAlea.nextInt(5));

System.out.println(suiteAlea.nextInt());

System.out.println(suiteAlea.nextFloat());

System.out.println(suiteAlea.nextBoolean());

Conventions d’écriture du code

class CompteEnBanque methode

– crediterCompte(25)– getSolde()– setSolde(10)

variable– empruntCourant

Constante– TAUX_INTERET

Java les respecte donc respectez-les !!

Contrôle du Flux d’instructions

Sans contrôle du flux• les instructions sont exécutées dans l’ordre où

elles apparaissent dans le fichier source

Contrôler le flux pour• Exécuter conditionnellement des instructions• Exécuter de façon répétitive un bloc de code

Les Instructions de Contrôle

if

switch

for

while do-while

break

continue

return

Instructions de Contrôle

Instruction while

On utilise l'instruction while pour exécuter répétitivement un bloc de code tant qu'une condition reste vraie

while (expression) { instructions }

On commence par évaluer l'expression, qui doit retourner une valeur booléenne

Si expression retourne true, alors on exécute les instructions associées

L'instruction while continue en testant expression et en exécutant les instructions jusqu'à ce que expression retourne false

Instruction while

Ce programme utilise une instruction while pour parcourir une String, copiant les caractères dans un buffer jusqu'à rencontrer la lettre 'g'

String copyFromMe = "Copy this string until you encounter the letter 'g'.";

StringBuffer copyToMe = new StringBuffer();int i=0;char c=copyFromMe.charAt(i);while (c != 'g') {

copyToMe.append(c); i=i+1;c = copyFromMe.charAt(i);

}S.o.p(copyToMe);

Valeur affichée par S.o.p ?

Instruction do-while

Java fournit une autre structure similaire do-while

do {instructions}

while(expression);

expression est évaluée à la base de la boucle les instructions associées sont donc exécutées

au moins une fois

Instruction do-while

String copyFromMe = "Copy this string until you encounter the letter 'g'.";

StringBuffer copyToMe = new StringBuffer();int i=0;char c ;do {

c = copyFromMe.charAt(i);copyToMe.append(c);i=i+1 ;

}while (c != 'g');S.o.p(copyToMe);

Valeur affichée par S.o.p ?

Instruction for

for(initialisation;terminaison;incrément){instructions}

initialisation initialise la boucle ; exécuté une seule fois au début de la boucle

terminaison détermine quand terminer la boucle– évaluée au début de chaque itération– Quand l'expression retourne false, la boucle se termine

incrément exécutée à la fin de chaque itération

Souvent utilisé pour parcourir les éléments d'un tableau (Array), ou les caractères d'une chaîne (String)

Instruction for

int[] arrayOfInts = {32, 87, 3, 589};

for(int i=0; i<arrayOfInts.length; i++)

{

S.o.p(arrayOfInts[i] + " ");

}

Valeurs affichées par S.o.p ?

for vs. while

for(int i=0 ; i<arrayOfInts.length ; i++){

S.o.p(arrayOfInts[i] + " ");}

int i=0 ;while(i<arrayOfInts.length){

S.o.p(arrayOfInts[i] + " "); i++;

}

do {afficher(a)a = a+1;}

while (a != 10)

a = 1;do {

afficher(a)a = a+1 ;}

while (a != 10)

a = 10;do {

afficher(a)a = a+1;}

while (a != 10)

do {

afficher(a)

}

while (a != 10)

Garantir la fin des itérations

Question 1

Question 1

a==12

Question 2

Question 2

a=0a=0…

Question 3

Question 3

a=0

Question 4

Question 4

j=0j=0…

Instructions if/else

if (reponse == OK) { // code to perform OK action

}

if (reponse == OK) {// code to perform OK action

}else {// code to perform Cancel action

}

Cascade de structure if …

int score = 76; char grade; if (score >= 90) { grade = 'A'; }else // score < 90

if (score >= 80) { grade = 'B'; }else // score < 80if (score >= 70) { grade = 'C'; }else // score < 70if (score >= 60) { grade = 'D'; } else // score < 60{ grade = 'F'; }

S.o.p("Grade = " + grade);

Valeur affichée par S.o.p ?

Instruction switch

Permet d'exécuter, conditionnellement à la valeur d'un entier, certaines instructions

int mois = 10;switch (mois) {

case 1: S.o.p("Janvier") ; break;case 2: S.o.p("Février") ; break;case 3: S.o.p("Mars") ; break;…case 10: S.o.p("Octobre") ; break;case 11: S.o.p("Novembre") ; break;case 12: S.o.p("Décembre") ; break;default: S.o.p("non valide!");

}Valeur affichée par S.o.p ?

Un exemple …

Un programme qui permette de :

Saisir deux nombres réels au clavier Afficher un menu à l'écran

S)omme des deux nombresP)roduit des deux nombresM)oyenne des deux nombres

Saisir le choix de l'utilisateur, ‘S', 'P' ou 'M‘ Afficher le résultat correspondant

import unsa.Console;

public class Exo {

public static void main(String [] args) {

float nb1= Console.readFloat("Entrer un nombre réel : ");

float nb2= Console.readFloat("Entrer un nombre réel : ");

S.o.p("*****************************");

S.o.p("* S)omme des deux nombres *");

S.o.p("* P)roduit des deux nombres *");

S.o.p("* M)oyenne des deux nombres *");

S.o.p("*****************************");

switch (Console.readChar("Faites votre choix")) {

case 'S' : S.o.p(nb1+nb2);break;

case ‘P' : S.o.p(nb1*nb2);break;

case ‘M' : S.o.p((nb1+nb2)/2);break;

default : S.o.p("erreur de saisie");

}

System.exit(0);}

}

import unsa.Console;public class Exo { public static void main(String [] args) { float nb1= Console.readFloat("Entrer un nombre réel : "); float nb2= Console.readFloat("Entrer un nombre réel : "); S.o.p("*****************************"); S.o.p("* S)omme des deux nombres *"); S.o.p("* P)roduit des deux nombres *"); S.o.p("* M)oyenne des deux nombres *"); S.o.p("*****************************"); switch (Console.readChar("Faites votre choix")) { case 'S' :

case 's' : S.o.p(nb1+nb2);break; case ‘P' :

case ‘p' : S.o.p(nb1*nb2);break; case 'm' :

case 'M' : S.o.p((nb1+nb2)/2);break; default : S.o.p("erreur de saisie");

} System.exit(0);}}

public static void main(String [] args) {

float nb1= Console.readFloat("Entrer un nombre réel : ");

float nb2= Console.readFloat("Entrer un nombre réel : ");

S.o.p("*****************************");

S.o.p("* S)omme des deux nombres *");

S.o.p("* P)roduit des deux nombres *");

S.o.p("* M)oyenne des deux nombres *");

S.o.p("*****************************");

switch (Character.toLowerCase(Console.readChar("choix ?"))) {

case ‘s': S.o.p("somme : "+(nb1+nb2)) ;break;

case ‘p': S.o.p("produit: "+(nb1*nb2)) ;break;

case ‘m': S.o.p("moyenne: "+(nb1+nb2)/2);break;

default : S.o.p("erreur de saisie");

}

}

public static void main(String [] args) {

float nb1= Console.readFloat("Entrer un nombre réel : ");

float nb2= Console.readFloat("Entrer un nombre réel : ");

S.o.p("*****************************");

S.o.p("* S)omme des deux nombres *");

S.o.p("* P)roduit des deux nombres *");

S.o.p("* M)oyenne des deux nombres *");

S.o.p("*****************************");

char rep ;

do {

rep= Character.toLowerCase(Console.readChar("choix ?"));

switch (rep) {

case ‘s': S.o.p("somme : "+(nb1+nb2)) ;break;

case ‘p': S.o.p("produit: "+(nb1*nb2)) ;break;

case ‘m': S.o.p("moyenne: "+(nb1+nb2)/2);break;

default : S.o.p("erreur de saisie");

}

} while ((rep != 's') && (rep != 'p') && (rep != 'm')) ;

}

Conversion d'un caractère en minuscule

char rep ;

rep=Character.toLowerCase(Console.readChar("votre choix ?"));

S.o.p(rep);

Console.readChar("votre choix ?")

readChar est une méthode de la classe Console qui retourne le char lu au clavier

static char toLowerCase(char ch)

Méthode static de la classe Character : le caractère donnée char ch est converti en minuscule avant d'être retourné en résultat char

Il faut distinguer le type primitif char et la classe Character

Capitaliser un texte

Public static void main(String[] args) {

String str=Console.readLine("Tapez un texte");

char ch; // un caractère de str

char prevCh='.'; // le caractère précédent ch

for (int i = 0; i < str.length(); i++ ) {

ch = str.charAt(i);

if ( Character.isLetter(ch) &&

! Character.isLetter(prevCh) )

S.o.p( Character.toUpperCase(ch) );

else S.o.p(ch);

prevCh = ch;

}

}

Notion d'algorithme

une procédure de calcul bien définie qui prend en entrée une ou plusieurs valeurs et qui délivre en sortie un résultat

Exemples d'algorithmes – PGCD (Plus Grand Commun Diviseur)– Algorithmes de tri – Algorithmes de recherche

Recherche d'une chaîne de caractère dans un texte (Logiciels de traitement de texte).

Recherche dans un dictionnaire

Attention, certains problèmes n'admettent pas de solution algorithmique exacte et utilisable. On utilise dans ce cas des algorithmes heuristiques qui fournissent des solutions convenables.

Algorithme d’Euclide

PGCD (Plus Grand Commun Diviseur) de deux nombres u et v

– Algorithme naïf on teste successivement si chaque nombre entier est

diviseur commun

– Algorithme d'Euclide (IIIème siécle) pour calculer le pgcd de deux nombre entiers

Calculer le PGCD de deux entiers A et B

PGCD(A,B) = PGCD(B,R)

A = (B x Q) + R 0 <= R < B

294 = (231 x 1) + 63

231 = (63 x 3) + 42

63 = (42 x 1) + 21

42 = (21 x 2) + 0

PGCD(294,231) = 21

Algorithme d'Euclide

int a=21, b=14 ;int r ;S.o.p("PGCD "+a+" et "+b+"  = ");r=a%b;/* division euclidienne de a par b

a=b*q+r et 0 <= r < b */while (r!=0){

a=b ; b=r; // pgcd(a,b)=pgcd(b,r)r=a%b;

}S.o.p(b);

Algorithme d'Euclide

int pgcd(int a , int b)

{

int r = a%b;

if (r!=0) return pgcd(b,r) ;

else return b ;

}

Algorithme d'Euclide (version récursive)

public class Exo {

static int pgcd(int a, int b){ int r = a%b; if(r != 0) return pgcd(b,r); else return b ; } public static void main (String args []){ int x = 21 , y = 14 ; S.o.p("PGCD "+x+" et "+y+" est "+pgcd(x,y)); }}

Algorithme d'Euclide (version récursive)

public class Exo {

static int factoriel(int n){ if (n != 0) return n*factoriel(n-1);

else return 1 ; } public static void main (String args []){ int a = 4 ; S.o.p(a+"! = "+factoriel(a)); }}

Fonction Factoriel (version récursive)

public class Exo {

public static void main (String args []){

int n = 3 ;

int fact = 1 ;

for(int i=2 ; i <= n ; i++) fact=fact*i ;

S.o.p(n+"! = "+fact) ;

}

}

Fonction Factoriel (version itérative)

public class Exo {

public static void main (String args []){

int n = 3 ;

int fact = 1 ;

for(int i=2 ; i <= n ; i++) fact=fact*i ;

S.o.p(n+"! = "+fact) ;

}

}

Fonction Factoriel (version itérative)

public class Exo {

public static void main (String args []){ byte n = ? ; S.o.p(n+"! = "+fact(n)) ;

short n = ? ; S.o.p(n+"! = "+fact(n)) ;

int n = ? ; S.o.p(n+"! = "+fact(n)) ;

long n = ? ; S.o.p(n+"! = "+fact(n)) ; }}

Le plus grand Factoriel ?

Byte n = 5 ; // 2^7-1 = 127

S.o.p(n+"!="+fact) ; // 5! = 120

short n = 7 ; // 2^15-1 = 32 767

S.o.p(n+"!="+fact) ; // 7! = 5 040

Le plus grand Factoriel ?

int n = 12 ;

// 2^31-1 = 2 147 438 647

S.o.p(n+"!="+fact);

// 12! = 479 001 600

// 13! = 6 227 020 800

Le plus grand Factoriel ?

Quand doit-on écrire les tests ?

eXtreme Programming Pratique la plus en vogue aujourd'hui Ecrire les tests avant même de commencer à coder Pair programming (programmation en binôme)

– discussion du binôme autour de développement à effectuer (on ne parle pas des 5 jours à venir mais des 30 minutes à venir)

– l'un des développeurs écrit les tests, tandis que l'autre implémente

Le framework de tests unitaires JUnit

Développé en Java par Kent Beck (initiateur de XP) et Erich Gamma (initiateurs des Design Patterns).

http://download.sourceforge.net/junit/junit3.8.1.zip

Objectifs de JUnit Tester des applications Java Faciliter la création de ces tests Tests de non régression Exécuter automatiquement des tests Obtenir un feedback rapidement Ecrire du code de qualité plus rapidement

public class Exo {

static int factoriel(int n){ if (n != 0) return n*factoriel(n-1);

else return 1 ; } public static void main (String args []){ int a = 4 ; S.o.p(a+"! = "+factoriel(a)); }}

Comment tester la fonction factoriel !

Junit : un framework de tests unitaires

import junit.framework.TestCase;public class FactorielTest extends TestCase {

public void test0() { Exo t = new Exo(); int attendu = 1; // 0! int actuel = t.factoriel(0); assertEquals("factoriel 0", attendu, actuel);} public void test1() { Exo t = new Exo();

int attendu = 120; // 5! int actuel = t.factoriel(5); assertEquals("factoriel 5", attendu, actuel);}}

Un TestRunner permet de lancer l'exécution des Tests

public static void main(String[] args) {junit.textui.TestRunner.run(FactorielTest.class); }

public static void main(String[] args) {junit.awtui.TestRunner.run(FactorielTest.class); }

public static void main(String[] args) {junit.swingui.TestRunner.run(FactorielTest.class); }

Tests unitaires avec Junit

import junit.framework.TestCase;

public class FactorielTest extends TestCase { public void test2() { Exo t = new Exo(); int n=5 ; int actuel = t.factoriel(n)/t.factoriel(n-1); int attendu = n; assertEquals("5!/4!", attendu, actuel); }}

Tests unitaires avec Junit

import junit.framework.TestCase;public class FactorielTest extends TestCase {

public void test3() { Exo t = new Exo(); int actuel = t.factoriel(17); assertTrue(actuel>0); }}

Le nombre Mystérieux

public static void main (String args[]){int inconnu = (int) (Math.random()*100);int score=0;int prop=Console.readInt("proposition :"); score++;while (prop != inconnu){

if (prop < inconnu)S.o.p("TROP PETIT");

else S.o.p("TROP GRAND");prop=Console.readInt("proposition :"); score+

+;}S.o.p("Vous avez trouvé en "+score+" coups");System.exit(0);

}

La classe String

String str = "abc";

char str[] = {'a', 'b', 'c'};

String str = new String("abc");

int length() – Returns the length of this string

String str = "abc";

S.o.p(str.length());

char charAt(int index)

Parameters: index - the index of the character

Returns: the character at the specified index of this string. The first

character is at index 0

Throws: IndexOutOfBoundsException - if the index argument is

negative or not less than the length of this string

String str = "abc";

S.o.p(str.charAt(2));

int compareTo(String anotherString)

Parameters: – anotherString - the String to be compared

Returns: – the value 0 if the argument string is equal to this string– a value less than 0 if this string is lexicographically less than

the string argument– a value greater than 0 if this string is lexicographically

greater than the string argument

Throws: – NullPointerException - if anotherString is null

int indexOf(int ch)

Parameters: – ch - a character

Returns: – the index of the first occurrence of the character in the

character sequence represented by this object– or -1 if the character does not occur

String str = "abcb";

S.o.p(str.indexOf(’b’));

int indexOf(String str)

Parameters: – str - any string.

Returns: – if the string argument occurs as a substring within this object,

then the index of the first character of the first such substring is returned

– if it does not occur as a substring, -1 is returned

Throws: – NullPointerException - if str is null

String str = "abcabc";S.o.p(str.indexOf("bc"));

String substring(int beginIndex)

Parameters: – beginIndex - the beginning index, inclusive

Returns: – the specified substring

Throws: – IndexOutOfBoundsException - if beginIndex is

negative or larger than the length of this String object

String substring(int beginIndex)

"unhappy".substring(2)

returns ?

"Harbison".substring(3)

returns ?

"emptiness".substring(9)

returns ?

String substring(int beginIndex)

"unhappy".substring(2)

returns "happy"

"Harbison".substring(3)

returns "bison"

"emptiness".substring(9)

returns "" (an empty string)

String substring(int beginIndex, int endIndex)

"hamburger".substring(4, 8)

returns ?

"smiles".substring(1, 5)

returns ?

String substring(int beginIndex, int endIndex)

"hamburger".substring(4, 8)

returns "urge"

"smiles".substring(1, 5)

returns "mile"

public String concat(String str)

Parameters: – str - the String that is concatenated to the end of this

String

Returns: – a string that represents the concatenation of this

object's characters followed by the string argument's characters

Throws: – NullPointerException - if str is null

public String concat(String str)

"cares".concat("s")

returns ? 

"to".concat("get").concat("her")

returns ?

public String concat(String str)

"cares".concat("s")

returns "caress"  

"to".concat("get").concat("her")

returns "together"

La classe StringBuffer

A string buffer is like a String, but can be modified

At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed

through certain method calls

StringBuffer append(String str)

Parameters: – str - a string

Returns: – a reference to this StringBuffer

StringBuffer str= "toto";

str.append("titi");

S.o.p(str);

StringBuffer replace(int start, int end, String str)

Parameters: – start - The beginning index, inclusive– end - The ending index, exclusive– str - String that will replace previous contents

Returns: – This string buffer

Throws: – StringIndexOutOfBoundsException - if start is

negative, greater than length(), or greater than end

StringBuffer reverse()

The character sequence contained in this string buffer is replaced by the reverse of the sequence

StringBuffer str = "esope";

S.o.p(str.reverse());

É s o p e r e s t er e s t e i c i e te t s e r e p o s e

public static void main(String [] args) { String phrase=Console.readLine("Entrez une string");

final int taille = phrase.length();int i = 0, j = taille - 1;while(i<taille/2 &&

phrase.charAt(i) == phrase.charAt(j)) {i++ ; j-- ;}

if (i >= taille/2) S.o.p(phrase+" est un palindrome");

else S.o.p (phrase+" n’est pas un palindrome");

System.exit(0);}

É s o p e r e s t er e s t e i c i e te t s e r e p o s e

public static void main(String [] args) { String phrase=Console.readLine("votre

texte").toUpperCase();

StringBuffer sb1 = new StringBuffer(phrase);

StringBuffer sb2 = new StringBuffer(phrase);

sb1.reverse();

if (sb1.toString().equals(sb2.toString()))

S.o.p(phrase+" est un palindrome");

else S.o.p(phrase+" n'est pas un palindrome");

System.exit(0);

}

On aligne n boules, réparties en un nombre quelconque de boules bleues, blanches ou rouges, disposées dans un ordre quelconque

Écrire un algorithme qui trie le tableau de telle façon que toutes les boules bleues apparaissent au début, suivies des boules blanches puis des boules rouges

Le tri doit être réalisé en unique parcours

Algorithme du drapeau tricolore

b ri

b i r

b i r

i r

int d[]={3,1,3,1,2,3,2,3,2,1};// 1=bleu 2=blanc 3=rougefor(int k=0 ; k<d.length ; k++) { S.o.p(d[k]+" ");}

int i=0 , b=0 , r=d.length-1 ;while ( i <= r ) { switch (d[i]) {

case 1 : echanger(b,i); b++;i++;break; case 2 : i++; break;

case 3 : echanger(r,i); r--; break; }}

S.o.p("le drapeau ..."); for(int k=0 ; k<d.length ; k++) { S.o.p(d[k]+" ");}

Algorithme du drapeau tricolore

Comment les arguments sont-ils passés aux méthodes ?

public class Demo {static void f(int b) {

b = 10;}

public static void main(String [] args) { int a = 5; f(a); S.o.p("a = " + a); }}

// Quelle est la valeur affichée, 5 ou 10 ?

Comment les arguments sont-ils passés aux méthodes ?

public class Demo {static void f(int a) {

a = 10;}

public static void main(String [] args) { int a = 5; f(a); S.o.p("a = " + a); }}

// Quelle est la valeur affichée, 5 ou 10 ?

Passage des arguments par valeurpublic class Demo {static void f(int a) {

a = 10;S.o.p("a de f= " + a);

}

public static void main(String args[]) { int a = 5; f(a); S.o.p("a du main = " + a); }}

Passage des arguments par valeurpublic class Demo {static void echanger(int i, int j) {

int aux=i ; i=j; j=aux ;}

public static void main(String args[]) { int a = 5 , b=10 ; S.o.p("a = " + a+" b = " + b);

echanger(a,b);S.o.p("a = " + a+" b = " + b);

}}

Passage d'un objet en argumentpublic class Demo {

static void echanger(StringBuffer i, StringBuffer j) {

StringBuffer aux=new StringBuffer(j.toString());

j.replace(0, j.length(), i.toString()) ;

i.replace(0, i.length(), aux.toString()) ;}

public static void main(String args[]) {

StringBuffer a = new StringBuffer("totoToto") ;

StringBuffer b = new StringBuffer("titi") ;

S.o.p("a = " + a+" et b = " + b);

echanger(a,b);

S.o.p("a = " + a+" et b = " + b);

}

}

Passage d'un objet en argumentstatic void lireTableau(int tLu[]){

for (int i=0 ; i<tLu.length ; i++) tLu[i] = Console.readInt("Taper un entier : ");

}static void afficherTableau(int tAf[]){

for (int i=0;i<tAf.length;i++) S.o.p(tAf[i] + " ");}public static void main(String [] args){

final int TAILLE=5;int tableau [] = new int[TAILLE];lireTableau(tableau);afficherTableau(tableau);System.exit(0);

}

top related