Partie 3: Contrôle d'Exécution — Programmation orientée objet en C++

Post on 20-Jun-2015

646 views 1 download

description

Support material for a continued education course "Introduction to object oriented programming in C++". In French.

Transcript of Partie 3: Contrôle d'Exécution — Programmation orientée objet en C++

Fabio HernandezFabio.Hernandez@in2p3.fr

Programmation Orientée Objet en C++Programmation Orientée Objet en C++

3ème Partie: Instructions de Contrôle d’Exécution3ème Partie: Instructions de Contrôle d’Exécution

© 1997-2003 Fabio HERNANDEZ78POO en C++: Contrôle d’Exécution

Vue d'EnsembleVue d'Ensemble

Notions de base Types, variables, opérateursContrôle d'exécutionFonctionsMémoire dynamiqueQualité du logicielEvolution du modèle objet Objets et classesFonctions membresClasses génériquesHéritagePolymorphismeHéritage multipleEntrée/sortie

© 1997-2003 Fabio HERNANDEZ79POO en C++: Contrôle d’Exécution

Table des MatièresTable des Matières

Instructions de Sélection (if, switch)Instructions d’Itération (while, for, do)Instruction de Rupture (break, continue)

© 1997-2003 Fabio HERNANDEZ80POO en C++: Contrôle d’Exécution

Instructions de Sélection: Instructions de Sélection: if

Forme généraleif (condition)

instruction

if (condition) {instruction 1instruction 2....instruction n

}

© 1997-2003 Fabio HERNANDEZ81POO en C++: Contrôle d’Exécution

Instructions de Sélection: Instructions de Sélection: if (suite)(suite)

Forme générale (suite)if (condition)

instruction 1else

instruction 2

if (condition) {instruction 1....instruction n

}else {

instruction 1....instruction n

}

© 1997-2003 Fabio HERNANDEZ82POO en C++: Contrôle d’Exécution

Instructions de Sélection: Instructions de Sélection: if (suite)(suite)

Exemplesune seule instructionif (temperature > 50.0)

cout << "this is getting HOT..." << endl;

plusieurs instructionsif (temperature > 90.0) {

threshold = temperature;

cout << "WARNING: evacuation is inminent" << endl;

}

© 1997-2003 Fabio HERNANDEZ83POO en C++: Contrôle d’Exécution

Instructions de Sélection: Instructions de Sélection: if (suite)(suite)

La condition est une expression qui produit une valeur de faux (zéro) ou vraie(non zéro)

Un entier ou un pointeur peuvent être utilisés comme conditionsExempleint count;if (count){

// do something}

est équivalent àif (count != 0) {

// do something}

De façon similaire pour les pointeursint* aPointer;

if (aPointer) // equivalent to if (aPointer != 0)

// do something

© 1997-2003 Fabio HERNANDEZ84POO en C++: Contrôle d’Exécution

Instructions de Sélection: Instructions de Sélection: if (suite)(suite)

Rappel 1: les expressions comprenant des opérateurs logiques && (ET) et || (OU) sont évaluées de gauche à droite et uniquement le nombre de composants nécessaires pour déterminer la valeur de vérité de la condition sont évaluésRappel 2: on ne peut pas déréférencer un pointer nul

On peut donc écrireint* aPointer;

if (aPointer && (*aPointer > 100)) {

// do something

}

Si aPointer == 0 la deuxième partie de la condition n’est pas évaluée

© 1997-2003 Fabio HERNANDEZ85POO en C++: Contrôle d’Exécution

Instructions de Sélection: Instructions de Sélection: ifif (suite)(suite)

Parfoisun if simple commeif (a <= b)

min = a;else

min = b;

peut être mieux exprimé parmin = (a <= b) ? a : b;

à utiliser uniquement pour des expressions simples autrement, le code peut devenir illisible

© 1997-2003 Fabio HERNANDEZ86POO en C++: Contrôle d’Exécution

Instructions de Sélection:Instructions de Sélection: switch

Une suite de if...else peut être écrite plus simplement à l’aide de l’instruction switch

Exemple: déterminer le nombre d’occurrences des lettres ‘a’ et ‘e’ dans un texteAvec ifchar letter;int aCounter=0;int eCounter=0;int other=0;...if (letter == ‘a’)

++aCounter;else if (letter == ‘e’)

++eCounter;else

++other;

© 1997-2003 Fabio HERNANDEZ87POO en C++: Contrôle d’Exécution

Instructions de Sélection:Instructions de Sélection: switch (suite)(suite)

Avec switchswitch (letter) {

case ‘a’:++aCounter;break;

case ‘e’:++eCounter;break;

default:++other;break;

}

© 1997-2003 Fabio HERNANDEZ88POO en C++: Contrôle d’Exécution

Instructions de Sélection:Instructions de Sélection: switch (suite)(suite)

Exemple: déterminer le nombre de voyelles dans un texteint vowelCounter = 0;int other = 0;switch (letter) {

case ‘a’:case ‘e’:case ‘i’:case ‘o’:case ‘u’:

++vowelCounter;break;

default:++other;break;

}

© 1997-2003 Fabio HERNANDEZ89POO en C++: Contrôle d’Exécution

Instructions de Sélection:Instructions de Sélection: switch (suite)(suite)

Attention: chaque entrée case dans un switch doit êtredelimitée, autrement l’execution continue sequentiellement

Exempleint value;....switch (value) { // WARNING: no break

case 1:cout << "entering case 1" << endl;

case 2:cout << "entering case 2" << endl;

default:cout << "unknown value" << endl;

}

© 1997-2003 Fabio HERNANDEZ90POO en C++: Contrôle d’Exécution

Instructions de Sélection:Instructions de Sélection: switch (suite)(suite)

Si au moment d’executer le switch, la valeur de value est 1, le résultat est

entering case 1entering case 2unknown value

© 1997-2003 Fabio HERNANDEZ91POO en C++: Contrôle d’Exécution

Instructions de Sélection:Instructions de Sélection: switch (suite)(suite)

Comparez contreint value;....switch (value) {

case 1:cout << "entering case 1" << endl;break;

case 2:cout << "entering case 2" << endl;break;

default:cout << "unknown value" << endl;break;

}

© 1997-2003 Fabio HERNANDEZ92POO en C++: Contrôle d’Exécution

Contrôle d'AvancementContrôle d'Avancement

Instructions de Sélection (if, switch)Instructions d’Itération (while, for, do) Instruction de Rupture (break, continue)

© 1997-2003 Fabio HERNANDEZ93POO en C++: Contrôle d’Exécution

Instructions d’Itération:Instructions d’Itération: while

Forme généralewhile (condition)

instruction

while (condition) {

instruction 1...instruction n

}

Séquence d'exécution:evaluation de la conditionexécution des instructions du corps si la condition est vraie

Si la première évaluation de la condition donne faux, les instructions du corps ne sont jamais exécutées

© 1997-2003 Fabio HERNANDEZ94POO en C++: Contrôle d’Exécution

Instructions d’Itération:Instructions d’Itération: while (suite)

Etant donné:typedef float Temperature;const int NumRooms = 100;Temperature room[NumRooms];

Exemple 1: donner une valeur initiale à toutes les positions du tableau room

Solution 1:int roomNumber=0;const Temperature InitialTemp = 15.0;while (roomNumber < NumRooms) {

room[roomNumber] = InitialTemp;roomNumber += 1;

}

© 1997-2003 Fabio HERNANDEZ95POO en C++: Contrôle d’Exécution

Instructions d’Itération:Instructions d’Itération: while (suite)

Solution 2while (roomNumber < NumRooms) {

room[roomNumber] = InitialTemp;roomNumber++;

}

Solution 3while (roomNumber < NumRooms)

room[roomNumber++] = InitialTemp;

© 1997-2003 Fabio HERNANDEZ96POO en C++: Contrôle d’Exécution

Instructions d’Itération:Instructions d’Itération: while (suite)

Exemple 2: chercher les valeurs maximum et minimum dans le tableau room

#include <float.h>

int roomNumber=0;

Temperature max = FLT_MIN;

Temperature min = FLT_MAX;

while (roomNumber < NumRooms) {

if (room[roomNumber] > max)

max = room[roomNumber];

else if (room[roomNumber] < min)

min = room[roomNumber];

roomNumber++;

}

© 1997-2003 Fabio HERNANDEZ97POO en C++: Contrôle d’Exécution

Instructions d’Itération: Instructions d’Itération: for

Forme généralefor (init-expresssion; condition; expression)

instructionfor (init-expresssion; condition; expression) {

instruction 1...instruction n

}

init-expression est executé une fois avant de commencer la bouclesi l’évaluation de condition est vraie le corps du for est exécuté expression est executé à chaque itération, après le corps

© 1997-2003 Fabio HERNANDEZ98POO en C++: Contrôle d’Exécution

Instructions d’Itération: Instructions d’Itération: for (suite)

La condition doit être évaluée vrai après l’exécution de init-expression pour que la boucle soit exécutée au moins une foisExemples: etant donné:

typedef float Temperature;const int NumRooms = 100;Temperature room[NumRooms];

Exemple 1: donner une valeur initiale à toutes les positions du tableau room

Solution 1:int roomNumber;const Temperature InitialTemp = 15.0;for (roomNumber=0; roomNumber < NumRooms; ++roomNumber)

room[roomNumber] = InitialTemp;

© 1997-2003 Fabio HERNANDEZ99POO en C++: Contrôle d’Exécution

Instructions d’Itération: Instructions d’Itération: for (suite)

Exemple 2: chercher les valeurs maximum et minimum dans le tableau room

Solution 1#include <float.h>

int roomNumber;

Temperature max = FLT_MIN;

Temperature min = FLT_MAX;

for(roomNumber=0; roomNumber < NumRooms; ++roomNumber){

if (room[roomNumber] > max)

max = room[roomNumber];

else if (room[roomNumber] < min)

min = room[roomNumber];

}

© 1997-2003 Fabio HERNANDEZ100POO en C++: Contrôle d’Exécution

Instructions d’Itération: Instructions d’Itération: for (suite)

Une boucle sans fin peut être écritefor (;;) {

// do something forever}

init-expression et expression peuvent être composées de plusieurs instructions, comme dans...

for (i=0, j=100; array[i] < max; i++, j--)

...ou peuvent ne pas existerint i=0;

int j=100;

for (; array[i] < max; i++, j--) // null init-expression

© 1997-2003 Fabio HERNANDEZ101POO en C++: Contrôle d’Exécution

Instructions d’Itération: Instructions d’Itération: do

Forme généraledo {

instruction 1...instruction n

} while (condition);

La condition est évaluée après l’exécution du corpsLa boucle est donc exécutée au moins une fois

© 1997-2003 Fabio HERNANDEZ102POO en C++: Contrôle d’Exécution

Contrôle d'AvancementContrôle d'Avancement

Instructions de Sélection (if, switch)Instructions d’Itération (while, for, do) Instruction de Rupture (break, continue)

© 1997-2003 Fabio HERNANDEZ103POO en C++: Contrôle d’Exécution

Instructions de Rupture: Instructions de Rupture: break

Termine l’exécution du for, while, do ou switch le plus interneL’exécution reprend immediatement après le bloc terminé

Exemple: déterminer l’occurrence d’une valeur particulière dans un tableau; si trouvé écrire sa position

const int ArraySize = 200;int array[ArraySize];const int Target = 3456;int i;.....for (i=0; i < ArraySize; i++)

if (array[i] == Target)break;

if (i == ArraySize)cout << "Not found" << endl;

elsecout << "Target found at position " << i << endl;

Rupture d'exécution de la

boucle

© 1997-2003 Fabio HERNANDEZ104POO en C++: Contrôle d’Exécution

Instructions de Rupture: Instructions de Rupture: continue

Termine l’exécution de l’itération courante du for, while ou do le plus interneDans le cas du while et do, l’exécution reprend avec l’évaluation de la conditionDans le cas du for, l’exécution reprend avec l’exécution de expression

© 1997-2003 Fabio HERNANDEZ105POO en C++: Contrôle d’Exécution

Instructions de Rupture: Instructions de Rupture: continue (suite)

Exemple: modifier toutes les positions d’un tableau si sa valeurse trouve dans un intervalle donné

const int ArraySize = 200;int array[ArraySize];const int Start = 5000;const int End = 10000;.....for (int i=0; i < ArraySize; i++) {

// Do we need to modify this value?if ((array[i] < Start) || (array[i] > End))

continue; // nothing to do with this position

// modify this positionarray[i] /= 2;

}

© 1997-2003 Fabio HERNANDEZ106POO en C++: Contrôle d’Exécution

Contrôle d'AvancementContrôle d'Avancement

Instructions de Sélection (if, switch)Instructions d’Itération (while, for, do) Instruction de Rupture (break, continue)