122
Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Notions de Programmation Programmation en C en C Ludovic SIMON Ludovic SIMON ESE, LCPC ESE, LCPC L3 : LE315 Resp : M. Xavier Clady Année 2008/2009 Sur la base des Cours de Messieurs Benosman, Clady, Gas et Nègre

Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

  • Upload
    phambao

  • View
    221

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 1/122

Notions de Notions de ProgrammationProgrammation en C en CLudovic SIMONLudovic SIMON

ESE, LCPCESE, LCPC

L3 : LE315Resp : M. Xavier Clady

Année 2008/2009

Sur la base des Cours de Messieurs Benosman, Clady, Gas et Nègre

Page 2: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 2/122

Sommaire

Algorithme et Programmation

Compilation et Exécution

Les structures de contrôle

Les types

Fonctions et Procédures

Opérateurs et expressions

Pointeurs

Tableaux et Algorithmes de tri

Chaînes de caractères

Gestion dynamique de la mémoire

Structures et Listes Chaînées

Page 3: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 3/122

Algorithme et Programmation

Page 4: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 4/122

Pourquoi un algorithme? Programmer = communiquer avec une machine pour résoudre un problème

Pas de traduction directe vers un langage de programmation, sinon : Programmation à « essai successifs » ou au « coup par coup »; perte de temps Solutions spécifiques au langage; perte de généralité Lisibilité, maintenance, réutilisation amoindries

Outils à disposition : Une machine : ne fait que ce qu'on lui dit de faire Des périphériques d'entrées/sorties Des langages de programmation

Écrire un programme = donner à la machine une suite d'ordres dans un certain langage qui, en s'enchaînant, produiront des résultats à partir des données fournies pas l'utilisateur du programme, via les Entrées/Sorties.

L'analyse ne conduit pas à un programme mais à une étape intermédiaire permettant de réduire les trois défauts précédent : L'algorithme

Trouver l'enchaînement = analyser le problème posé en langage naturel puis le traduire.

Page 5: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 5/122

Algorithme Définition : suite d'instructions exprimées dans un pseudo-langage et

s'exécutant séquentiellement (une instruction à la fois et dans un ordre donné). Cette exécution apparaît comme une transformation de données du problème en résultats.

Pseudo-langage : langage plus restreint que le langage naturel et plus précisLes instructions s'expriment soit :

Par un ordre du langage ex:  affectation : a=3 Par une phrase en style abrégé ex:  copier la valeur X dans Y 

Le pseudo-langage tient compte des outils qu'offre la machine : mémoire, clavier, écran, ...Il précise le dialogue avec « l'extérieur » :

- données du problème et leur domaine de définition- résultats et leur domaine de définition

Exemple :Multiplier deux entiers>=0Données : A,BRésultat : CC = A x B;

Page 6: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 6/122

Analyse descendante Règle : Diviser pour mieux régner ! Niccolà Machiavelli, Le Prince

Sun Tzu, L'art de la guerreDijkstra : «  La difficulté de comprendre un programme d'un seul tenant croit exponentiellement en fonction de la taille du programme. »Descartes, Discours de la méthode : « Diviser chacune des difficultés que j'examinerais en autant de parcelles qu'il se peut et qu'il serait requis pour mieux le résoudre. »

A partir d'un problème complexe : 1) le décomposer en un ensemble de sous problèmes plus simples. 2) pour chaque sous problèmes :

Si il ne nécessite plus de décomposition, on le spécifie Sinon, on le considère comme un problème et on applique le 1)

Spécifier un problème : 1) Extraire les données 2) Déterminer les résultats à obtenir 3) Exprimer en quelques phrases le principe de résolution 4) Traduire le principe en algorithme via le pseudo-langage

Page 7: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 7/122

Programmation Traduire un algorithme en un certain langage

Règles à respecter :

Une seul instruction par ligne

L'enchaînement des instructions doit être facile à suivre

Utiliser les tabulations pour les blocs imbriqués

Choisir des noms de variables judicieux

Placer des commentaires pertinents

La traduction est conditionné par les spécificités du langage, en conservant l'idée directrice de l'algorithme

Un programme clair est préférable à un programme dit « astucieux » par son auteur mais « spaghetti » par ceux qui tentent de le comprendre

Page 8: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 8/122

Structure de base d'un programme C

type main (){

type1 nom1, nom2;...instruction1;instruction2;...

}

Nom de la fonction principale

Séparateur obligatoire

Variable du programme

Zone de déclarationdes variables

Type : Domaine de des variables (int, float, double, char, etc.)Mots réservés : Mots du langage utilisés dans un sens précis (main, for, int, etc.)

Instructions duProgramme

Fin de fonction

Début de fonction

Page 9: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 9/122

Initialiser et affecter Une variable, pour l'ordinateur, est un espace en mémoire centrale, de taille

définie (selon le type), dans lequel on pourra ranger de valeurs. Pour utiliser ce contenu, on utilise le nom de variable. Pour remplir ou modifier ce contenu, on utilise l'instruction d'affectation

Ex : a=2; contenu de a en mémoire : avant après? 2a=2;

L'affectation à pour rôle de remplir un espace. Elle écrase le contenu précédentLorsqu'une variable est déclarée, aucune valeur ne lui est affectée : son espace mémoire est indéterminé

Importance de l'initialisation des variables pour le bon déroulement du programme

int a;int b = 2;a = a + b;

? 2

a b?

? 2Pas d'erreur, Sauf à l'exécution !

Page 10: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 10/122

Échanger deux variables

=> Échanger le contenu de deux cases mémoires

Une troisième variable, temporaire, est obligatoire car l'affectation écrase le contenu

a tp

● Pseudo-langageÉchanger deux entiersDonnées : a,bRésultat : a,b

temp=a;a=b;b=temp;

● Langage Cvoid main (){

int a=1, b=2;int tp;

tp=a;a=b;b=tp;

}

b

Page 11: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 11/122

Périphérique d'entrée

=> Utiliser le clavier pour entrer une valeur et la ranger dans une variable

Mettre dans la variable A (espace mémoire )la valeur tapée au clavier

● Pseudo-langage...lire(A)...

● Langage C...

...d=format des entiers

Chaîne de formatage des données lues

Opérateur d'adressage

Nom de la fonctionde lecture au clavier

scanf(``%d'', &A);

Variable recevant la donnée

Lorsque scanf est exécutée, le programme se met en attente de donnéesprovenant du clavier. Lorsque la touche « retour » est tapé, les caractèresprécédents sont affectés au contenu de la variable.

Page 12: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 12/122

Périphérique de sortie

=> Afficher, à l'écran, la valeur contenu dans une variable

Lit le contenu de la variable A (sans la modifier ) et l'écrit sur l'écran

● Pseudo-langage...ecrire(A)...

● Langage C...

...

Format d'écriture des données sur l'écran

Séparateur

Nom de la fonctiond'écriture à l'écran

printf(``%d'', A);

Variable contenant la donnée

``...'' = chaîne de caractère``%... '' = défini les caractères qui suivent comme une chaîne de format

Page 13: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 13/122

Ex : Lecture / Écriture● Énoncé : Incrémenter une valeur entré au clavier puis afficher le résultat

● Analyse : Entrer la valeur. Ajouter 1 à la variable Afficher la variable.

● Algorithme : Ajouter 1Donnée : a : entierRésultat : a : entier

Lire(A);A = A+1;écrire(A);

● Programme C : void main()

{int a; // déclarationscanf(``%d'', &A); /* saisie et initialisation*/A++; /* incrément de A */printf(``%d'', A); // affichage

}

Page 14: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 14/122

Le mode conversationnel

Un programme en mode conversationnel contient des instructions permettant un dialogue entre l'utilisateur et le programme

La convivialité et l'ergonomie du programme dépend de la qualité de réalisation du mode conversationnel

Dans un programme, le dialogue utilisateur et les traitements sur les variables ne doivent jamais être confondus

Faire des fonctions qui réalisent des traitements spécifiqueset d'autres pour interagir avec l'utilisateur

Page 15: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 15/122

Compilation et Exécution

Page 16: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 16/122

Rendre le code source Exécutable

Page 17: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 17/122

Ex : Compilation sous Linux

Terminal (prompt interpréteur de commande)

[eleve@le315]$cc programme.c

[eleve@le315]$cc -c programme.c[eleve@le315]$cc -o programme.c programme.o[eleve@le315]$./programme[eleve@le315]$essai[eleve@le315]$

Programme...printf(``essai'');...

Le compilateur fait tout à la suite (compilation, édition, exécution)

CompilationÉdition de lienExécution

cc = compilateur C-c -o = option de compilation

-Wall = option pour montrer tous les « warnings »

Page 18: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 18/122

Normalisation

[eleve@le315]$cc -Wall program[eleve@le315]$prog.c:1: warning: return defaults to 'int'[eleve@le315]$prog.c: In function 'main':[eleve@le315]$prog.c:3: warning: implicit declaration of function 'printf'[eleve@le315]$prog.c:4: warning: control reaches end of a non-void function[eleve@le315]$

progmain(){

printf(``essai'');}

Exemples d'erreurs

Prog

#include <stdio.h>void main(){

printf(``essai'');return;

}

Librairie entrées/sorties standard

Bibliothèques :Fichiers d'en-tête (.h)Fichiers objets (.o)Fichier librairies (.a ou .dll ...)

Page 19: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 19/122

Forme générale d'un programme C

/* déclaration des bibliothèques */

/* définitions des constantes */

/* déclarations des variables globales */

int main(){

/* déclaration des variables locales */

/* corps du programme */

return(0);}

Écrire par Blocs et avec des Tabulations

Page 20: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 20/122

Les structures de Contrôle

Page 21: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 21/122

Types de Contrôle Instructions, Blocs

Une instruction se termine par un point-virgule (;) Les expressions (variables, constantes) peuvent être combinées ensemble à l'aide d'opérateur pour former des expressions plus complexes. Elles peuvent contenir des appels à des fonctions Elles peuvent être des paramètres d'appel des fonctions Différentes instructions peuvent êtres rassemblés en bloc à l'aide d'accolade ({et})

Sélection Test simple Test à choix multiple

Itérations Boucles

Ruptures Avec break

Page 22: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 22/122

Exécution Conditionnelle Un algorithme est une suite d'instructions séquentielles

Lorsque le traitement dépend des données, il est nécessaire d'utiliser des instructions conditionnelles

Il faut donc :Tester des valeursExécuter telle ou telle instruction en fonction du résultat du test

L'algorithme devient alors une synthèse de toutes les exécutions possibles

Ex : Calcul de la valeur absolue

ValAbsDonnée : A : entierRésultat : A: entiersi A<0 alorsA=-A;

Page 23: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 23/122

Conditionnelle

Simple ou Complète, Imbriqué ou Non Primitive : Si C Alors A

Syntaxe C : if (c) {a;}

if ( condition ){instruction1;instruction2;}

else{instruction3;instruction4;}

if ( condition1 )if ( condition2 )

instruction1;else

instruction2;

if ( condition1 ){if ( condition2 )

instruction1;else

instruction2;}

=

if ( condition1 )instruction1;

else{if ( condition2 )

instruction2;else

instruction3;}

if ( condition1 )instruction1;

else if ( condition2 )instruction2;

elseinstruction3;

=

Page 24: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 24/122

Exemples de Conditionnelles

Complète

Imbriqué

Simple

Page 25: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 25/122

Choix Multiple Primitive : Selon C faire

dans le cas où C=val1 : A1dans le cas où C=val2 : A2...sinon: Ax

Syntaxe C :

switch ( expression ){case constante1 :

instruction1.1;instruction1.2;

case constante2 :instruction2;

case constante3 :case constante4 :

instruction4.1;instruction4.2;

default :instructionD;

}

Permet une lisibilité accrue du programmelorsque beaucoup d'alternatives se présentent.

L'imbrication est peu recommandé

Page 26: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 26/122

Choix Multiple Exemple de la calculette :

Page 27: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 27/122

Itération Itérer =

Refaire plusieurs fois le même traitement sur un objetFaire des actions sur plusieurs objets identiquesModifier les objets sur lesquels l'action est répétée

Exemples :Afficher n fois le même caractèreAfficher toutes les notes d'un élèveCalculer la somme des n premier entiers

Il faut donc exercer un contrôle sur les instructions pour :Recommencer au bon endroitCompter le nombre d'itération et donc être capable de déterminer si oui ou non on doit recommencer

Page 28: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 28/122

Boucle « tant que » Primitive : Tant que C faire A

Syntaxe C :

Utilisée lorsque :

La progression de la condition n'est pas régulière

On ne sait pas au moment d'y entrer combien d'itérations sont à faire

C'est au programmeur de gérer l'évolution de la condition afin d'avoir une terminaison correcte de la boucle

En cas d'évaluation toujours vraie de la condition, le programme « boucle »

Si la valeur initiale de la condition est fausse, la boucle n'est pas exécutée

while ( condition ){instruction1;instruction2;}

Page 29: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 29/122

Boucle « tant que » Exemples :

Lire des nombres et les additionner, s'arrêter si le nombre lu vaut 99

Additionner les 20 premiers entiers pairs

Page 30: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 30/122

Boucle « faire ... tant que »

Primitive : Répéter A Tant que C

Syntaxe C :

Les instructions sont toujours exécutés au moins une fois

Si la condition est toujours vraie, on « boucle » indéfiniment

Si la valeur initiale de la condition est fausse, la boucle n'est pas exécutée

do{instruction1;instruction2;} while ( condition );

Page 31: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 31/122

Boucle « faire ... tant que » Exemples :

Lire des nombres et les additionner, s'arrêter si le nombre lu vaut 99

Additionner les 20 premiers entiers pairs

Page 32: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 32/122

Boucle « pour » (boucle avec compteur) Primitive : pour C faire A

Syntaxe C :

Utilisée lorsque : La progression de la condition est contrôléeOn sait au moment d'y entrer combien d'itérations sont à faire

C'est au programmeur de gérer l'évolution de la condition afin d'avoir une terminaison correcte de la boucle

Il ne doit pas être fait moins ou plus que ce qui était prévu au départ

S'il y a plusieurs instruction à répéter, les accolades sont obligatoires

Si la condition est fausse avant la boucle, il n'y a pas d'entré dans la boucle

Les instructions à répéter peuvent être des boucles imbriquées

for ( initialisation ; condition ; in(dé)crémentation ){

instruction1;instruction2;

}

Page 33: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 33/122

Exécution de la boucle « for »

for ( i=1 ; i<=10 ; i++ ){

instruction;}

1: initialisation de la variable de boucle2: test de la condition3: exécution si la condition est vraie4: sortie si la condition est fausse5: incrémentation (ou décrémentation)6: aller en 2

Page 34: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 34/122

Boucle « for » Exemple : Somme de 10 entiers successifs

Page 35: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 35/122

Rupture avec « Break »

Pour s'échapper d'une boucle ou d'un test à choix multiple Arrête une et une seule instruction itérative ou une sélection de

choix avant la fin normale

Syntaxe C :

while ( condition1 ){instruction1;if ( condition2 )

{instruction2;break;}

instruction3;}

Page 36: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 36/122

Balayage et sélection

Pour réaliser, à partir d'un ensemble de données, un traitement sur seulement certaines des données.

Le traitement par balayage et sélection consiste à parcourir toutes les données, pour tester celles qui doivent être traitées

Exemple : Entrer des nombres. Si le nombre est pair, l'afficher et le sommer. Afficher la somme. Le nombre 99 permettra de quitter le programme.

Page 37: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 37/122

Itération et récurrence

Récurrence : Une suite est récurrente lorsque chacun de ses termes (ui) est

défini par une fonction d'un ou plusieurs termes précédents et que le premier terme a une valeur connue et constante

Exemple : u0 = 0

ui = u

i-1+2

Itération = récurrence : Pour calculer le nème terme de la suite, nous devons faire l'opération (u

i = u

i-1+2) n fois afin de calculer tous les termes précédents :

u0 = 0

u1 = u

0+2

u2 = u

1+2

...u

n = u

n-1+2

Initialisation

N fois la même opération sur des objets différents

Algorithme

u=0;pour i=1 à n faire

u=u+2;

Page 38: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 38/122

Les types

Page 39: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 39/122

Notion de type

Pour programmer, on doit utiliser des « cases mémoires » pour stoker des informations

On associe des noms (explicite pour l'utilisateur) à ces cases (explicites pour l'ordinateur), les identificateurs

Ces noms obéissent à des règles :

Il n'est pas possible de mettre n'importe quelle donnée dans un nomIl n'est pas possible de faire n'importe quelle opération sur un nom

Pour toutes ces raisons, on définit le type d'une variable afin de spécifier son contenu

Page 40: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 40/122

Types du langage C

Définition : Un type défini, spécifie, l'ensemble des valeurs qui peuvent être affectées à un objet et détermine implicitement l'ensemble des opérations applicables à un objet

Syntaxe C (déclaration) :

Déclaration simple : Type identificateur;Déclaration avec initialisation : Type identificateur = valeur;Déclaration multiple : Type ident1, ident2=0, ident3=ident2;

TypeStructuréSimple

homogène hétérogènechar intshortlong

floatdouble

tableaux structuresigned ou unsigned

Page 41: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 41/122

Le type char

Définition : Le type char défini =t l'ensemble des caractères utilisés en informatique et codés selon le code ASCII

Syntaxe C (déclaration) :

char c;char c = 'A'; /* 'A' est une constante caractère */

Occupation mémoire : 1 octet soit 256 valeurs possibles

Codage des caractères : par des entiers signés (-128 à +127)

Affichage des caractères : printf(``c = \%c '', c) ;printf(``code ASCII de %c = \%d'', c, c) ;

Comment passer des minuscule au majuscule ....

Page 42: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 42/122

Le type booléen

Il n'existe pas en langage C !

On utilise la convention :

expression non nulle == vrai expression nulle == faux

Exemple :if (expression > 0) instruction;

si expression > 0 => (expression > 0)=1, donc instruction est réaliséesi expression <= 0 => (expression > 0)=0, donc instruction n'est pas réalisée

Page 43: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 43/122

Le type entier Il existe 3 types d'entiers pour les nombres

+ le type char : cas particulier d'entier sur 8 bits

Chaque type peut être signé ou non

Entiers signés

short int short 16 bits (2 octets)int ou int 16 ou 32 bits (mot machine)long int long 32 bits (4 octets)

Char short long+127 +32767 ← → +2,1475.10^9-128 -32768 ← → -2,1475.10^9

int

Bit de signe Représentation en base 2 (7, 15 ou 31 bits)

Page 44: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 44/122

Le type entier

Entiers non signés

Char short long255 65535 ← → 4,2950.10^90 0 ← → 0

int

Représentation en base 2 (8, 16 ou 32 bits)

Respect des types

unsigned int a= -10;

short int b = 65000;

unsigned int a = 65000;short int b = -10;a=b;

Constantes

● Entière : int a = 100;● Octale : short b = 010;● Hexa : long c = 0x2A;

Page 45: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 45/122

Le type réel

Permet de représenter, de manière approchée, une partie des nombres réels

Représentation en virgule flottante : Un nombre de bits est réservé pour chaque éléments (signe, mantisse, exposant)

signe mantisse signe exposant1 24 1 6

double 1 53 1 9long double 1 64 1 14

float

x=signe.mantisse.2signe.exposant

nombre réel signe partie fractionnaire positive

exposant signé

Page 46: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 46/122

Constante réelles Deux notations

float e = 3.14, f=4e-17, g = -10.23e-5;

double1,17.10^-38 2,22.10^-3083,40.10^+38 1,79.10^+308

float

Décimale Exponentielle

16.64-0.5.184.

4.25e45.27e-32

48e13-1.2e-10

Page 47: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 47/122

Opérateurs et expressions

Page 48: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 48/122

Expressions

Définition : une expression permet à partir d'un ensemble de valeurs, les opérandes, et d'un ensemble d'opérateurs, d'obtenir une nouvelle valeur

a = 10 / 5 ;a + 65000 ;a * b ;a = 10 ;b = ( a =10 ) ;b = a = 10 ;b = a * 100 ;b = b + 1 ;b++ ;c = b++ ;c = ( b = b + 1 ) ;

expression constante

l'affectation est une expression

l'incrémentation est une expression

écritures équivalentes

expression constante

Page 49: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 49/122

Opérateurs Le nombre d'opérande définit l'arité de l'opérateur En C, la plupart des opérateurs sont unaires ou binaires Des règles d'associativité et de priorité sont introduites afin de former

des expressions complexes Opérateurs arithmétiques par ordres de priorité :

* , / , % + , - , ++ , - -

Règles :Associativité à gauche : un opérande placé entre 2 opérateur de même priorité sera traité par celui de gauche :

5 – 4 + 3; <=> (5 – 4) + 3

Priorité : un opérande placé entre deux opérateurs de priorités différentes sera traité par l'opérateur de plus forte priorité :

5 + 4 * 3 <=> 5 + (4 * 3)

Une expression entre parenthèses sera toujours évaluée en priorité et son résultat sera utilisé comme opérande

Page 50: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 50/122

Opérateurs de relation

Comparateur d'expression2*a > b+5

Opérateurs de comparaison par ordres de priorité :< , <= , >= , > = = , !=

Ne pas confondre l'opérateur de relation = = avec l'opérateur de relation =

Page 51: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 51/122

Opérateurs logiques ET : && a<b && c>d vaut 1 si a<b ET c>d, 0 sinon

OU : | | a<b | | c>d vaut 1 si a<b OU c>d, 0 sinon

NON : ! !(a<b) vaut 1 si a>b, 0 sinon

Exemples : if(a!=0) if(!a) while (i!=0) while(!i)

Les expressions suivantes sont acceptées ! a&&2 a | | b !1

Priorités : !Opérateurs arithmétiquesOpérateurs relationnels

&&| |

Page 52: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 52/122

Exemple

Entrer des nombres. Si le nombre est pair, l'afficher et le sommer. Afficher la somme. Le nombre 99 permettra de quitter le programme.

Page 53: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 53/122

Opérateurs binaires Travail direct sur le motif binaire d'une valeur

Proches du langage assembleur

Ne s'appliquent que sur des entiersPour les autres types, il y a conversion « automatique » en entier

& ET logique | OU inclusif ^ OU exclusif<< Décalage à gauche>> Décalage à droite ~ Complément à 1

Utilisations :Décalages :

Masquages :

a = a<<2; 2 décalages à gaucheb = b>>5; 5 décalages à droiteb = a & 0xF; 4 derniers bits de droites pris en comptec = a & 0x8000; extraction du bit de signed = a & 1; extraction de la parité

hexa dec binaire op.0x056E 1390 0000010101101110 a0x03B3 947 0000001110110011 b0x0122 290 0000000100100010 a&b0x07FF 2047 0000011111111111 a | b0x06DD 1757 0000011011011101 a^b0xFA91 -1391 1111101010010001 ~a

Page 54: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 54/122

Permettent d'alléger l'écriture des programme. Opérateurs unaires.i++; i = i+1 ; j-- ; j = j-1 ;

Notation pré-fixée et post-fixée (pré et post incrémentation)++i; --j; i++; j--;

Exemples :

La priorité élevée supérieur à celle des opérateurs arithmétiques2*i++ * j-- + k++ (2*(i++) * (j--)) + (k++)

Opérateurs d'incrémentationet de décrémentation

int i = 2, a;a = ++i;a = i++;

i a

int i = 3, a;a = ++i – 3; a = i++ - 3;

i a

i a

Page 55: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 55/122

Permettent d'alléger l'écriture des programme. Opérateurs binaires (arité).i += j; i = i + j ;

Listes des opérateurs :

Opérateurs d'affectation élargie

arithmétiques+=-=*=/=

%=

binaires|=^=&=<<=>>=

Page 56: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 56/122

Permet d'alléger l'écriture des programme.

condition ? expression1 : expression2

if (condition)expression1;

elseexpression2;

Exemple : min = a<b ? a : b ;

Opérateur d'expression conditionnelle

Page 57: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 57/122

Certaines conversions de types sont « automatiques » : ce sont les promotions numériques :

char intshort intfloat double

Quand des opérandes de types différents sont évaluées dans une même expression, ils sont tous convertis en un seul et même type selon un nombre réduit de lois : ce sont les conversions implicites

Les seules conversions qui se font automatiquement sont celles qui donnent sens aux expressions :

Les Conversions Implicites

char c='A'; int d='a' – 'A';c = c + d;

int a=4; double b=.4;b = a + b;

int a=4; long b=40;b = a + b;

unsigned int a=4; int b;b = a + b;

Page 58: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 58/122

Utilisation de l'opérateur de changement de type, opérateur de cast

(type) expression

Exemples :

Priorité élévée :

Les Conversions Explicites

int a=10, b=3;double r;r = (double) (n/p) ; 3

r

int a=10, b=3;double r;r = (double) n/p ; 3,333

r

Page 59: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 59/122

Priorité des opérateurs( ) [ ] -> . ! ~ ++ -- (type) * & sizeof( ) * / % + -<< >> < <= > >=== != & ^ |&& | | ?: = += -= ......... '

La priorité de & ^ et | est inférieure à celles des == et !=

if ( (a & b) == 0)

Le résultat d 'un programme ne doit pas dépendre de l'ordre dévaluation des instructions

A[i] = i++;

Page 60: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 60/122

Fonctions et Procédures

Page 61: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 61/122

Principes et Avantages

Avantages d'un programme modulaire : Meilleure lisibilité Diminution du risque d'erreursPossibilité de tests sélectifsDissimulation des méthodesRéutilisation de modules déjà existantsSimplicité de l'entretienSimplification du travail en équipeHiérarchisation des modules ('topdown- development' - méthode du raffinement progressif) ou ('bottom-up-development') ou mixte ('jo-jo')

Diviser pour mieux régner ! Principe de l'analyse descendante Les fonctions permettent d'appliquer le principe de modularité Diviser les tâches importantes en tâches élémentaires Une fonction permet d'utiliser les résultats acquis par d'autres fonctions au

lieu de repartir de zéro Un programme constitué d'un grand nombre de petites fonctions est

préférable à un programme avec peu de fonctions mais de grandes tailles Le langage C a pour but de rendre les fonctions efficaces et faciles à utiliser

Page 62: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 62/122

Définition d'une fonction

typeRval nom_fonction ( type1 arg1, type2 arg2, ...){

déclaration des variables;...instructions;...return(Rval);

}

Nom de la fonction

Portée localesdes variables

Instructions de la fonction

Fin de fonction

Début de fonction

Type renvoyéArguments d'entrée

Exemple : fonctions min et max int max ( int a, int b ){

int lemax;

if ( a>b) lemax =a;else lemax = b;

return (lemax);}

int min ( int a, int b ){

if ( a>b) return a;else return b;

}

Page 63: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 63/122

Déclaration et Utilisation

type nom_fonction ( type1 arg1, type2 arg2, ...); Déclaration du prototype :

int max ( int a, int b );

int main(){

int x=2, y=4, lemax;

lemax = max (x,y);...return(0);

}

Utilisations :

Exemple :

type var;var = nom_fonction (arg1, arg2, ...);

nom_fonction(arg1, arg2, ...); /* forme procédurale*/

var = nom_fonction(); /* forme sans arguments */

Page 64: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 64/122

Transmission des arguments

La fonction appelée reçoit une copie provisoire, qui lui est propre, de chaque argument sans connaître leur adresse d'origine

Transmission par valeur :

int main(){

int x=2, y=4, lemin;

lemin = min (x,y);...return(0);

}

Exemple :

La fonction ne peut modifier l'argument qui lui est passé que localement

int min ( int a, int b ){

if ( a>b) return a;else return b;

}

10

Mémoire

1

Pile

10

1

x y

b

a

Page 65: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 65/122

Transmission des arguments

To be continued ...

Page 66: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 66/122

Les Macros Définition de symbole dans laquelle on utilise des arguments :

Exemples :

#define PRODUIT(X,Y) X * Y

void main(){

int i, j, k;float a, b, c, x;k = PRODUIT(i,j);c = PRODUIT(a,b);x = PRODUIT(5+i,b-a);

}

Le type n'est pas précisé !

k = i * j; /* soit (i*j) */c = a * b; /* soit (a*b) */x = 5 + i * b – a; /* soit (5+(i*b)-a) */

#define PRODUIT(X,Y) ((X) * (Y))

#define SOMij i + j != #define SOMij (i + j)

(5+i)*(b-a)

Page 67: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 67/122

Tableaux & Algorithmes de tri

Page 68: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 68/122

Définition : Ensemble d'éléments de même types désignés par un identificateur unique. Chaque élément est repéré par un indice précisant sa position au sein de l'ensemble

Déclaration :

Exemples :

Tableaux à un indice

type identificateur [dim]

Nom du tableauType des éléments Nombre d'éléments(expression constante)

#define DIM 50

int main(){

int tab1[DIM];float tab2[2*DIM - 1];...return(0);

}

constante

expression constante

Page 69: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 69/122

exemple#include <stdio.h>

#define NB_NOTES 20

void saisir_notes (int t[], int nb);

float moyenne (int t[], int nb){

float m; int i;for (i=0; i<nb; i++) m += t[i];return m/nb;

}

int main(){

int t[NB_NOTES];float moy;saisir_notes(t, NB_NOTES);moy = moyenne(t, NB_NOTES);printf(...);...return(0);

}

void saisir_notes(int t[], int nb){ }

void saisir_notes(int t[], int nb){

int i;for (i=0; i<nb; i++) {

printf(``donnez la note %d \n', nb);scanf(``%d'', &t[i]);

}}

.....................................

Contenu d'un élément du tableau : t[i]

Case 0Case 1 Case i Case NB_NOTES-1

Adresse d'un élément du tableau : &t[i]

Tableau t

Page 70: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 70/122

Un tableau n'est pas un type de base : les opérations globales sour les tableaux sont impossibles :

Initialisation :

Pas d'initialisation implicite

Attention aux débordements d'indices

Propriétés

int tab1[5];int tab2[] = {1,2,3,4,5};int tab3[10] = {1,2,3,4,5};int tab4[5] = {,,,4,5};

Pas d'erreur à la compilationErreur à l'exécution

int tabA[5], tabB[5]; tabA = tabB;

int tab[10];tab[10] = 11;

..................................... 11 ......

tab

Page 71: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 71/122

Un indice de tableau doit être de type entier :

Initialisation d'un tableau à l'éxécution (algorithme de parcours) :

Recherche du min (algorithme de recherche) :

Opérations sur les éléments d'un tableau

int tab[dim], i;for(i=0; i<dim; i++) tab[i] = 0; Parcours des éléments du tableau

int tab[10], n=1;tab[2] = 5;tab[n-1]++;tab[n--] = 0;tab[2*n+5] = 0;

int tab[dim], i, min;...min = tab[0];for(i=1; i<dim; i++)

if(tab[i]<min) min =tab[i];

Initialisation sur le 1er élément

Page 72: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 72/122

Tableau en argument de fonction

#include <stdio.h>

#define DIM 20

void raztab(int t[]);

int main(){

int tab[DIM];raztab(tab);...return(0);

}

void raztab(int t[]){

int i;for (i=0; i<DIM; t[i++]=0);

}

Seule l'adresse du tableau est transmise(pas de copie locale)

Dimension du tableau facultative

Raztab() ne travaille alors que sur des tableaux de dimension DIM

! Dangereux !

Page 73: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 73/122

Transmission de tableaux#define DIM 10#define DIM 200

void raztab(int t[], int d);void inittab(int t[], int d, int v);

int main(){

int tab1[DIM1], tab2[DIM2];;raztab(tab1, DIM1);raztab(tab2, DIM2);inittab(tab1, DIM1, 1);...return (0);

}

void raztab(int t[], int d){

int i;for (i=0; i<d; t[i++]=0);

}

void inittab(int t[], int d, int v){

int i;for (i=0; i<d; t[i++]=v);

}

La dimension est transmise en 2eme argument

Page 74: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 74/122

Recherche du min et du max d'un tableau

double getmin(double t[], int d){

int i;double lemin;

if (d = = 0)printf(``tableau vide'');

else{

lemin = t[0];for (i=1; i<d; i++)

if (t[i] < lemin)lemin = t[i];

}

return (lemin);}

int getmax(int t[], int d){

int i, lemax=-1;

if (d > 0){

lemax = t[0];for (i=1; i<d; i++)

if (t[i] > lemax)lemax = t[i];

}

return (lemax);}

Tableau de réels Tableau d'entiers positifs

Page 75: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 75/122

Recherche de l'indice du min (ou du max)

int getindmix(int t[], int d){

int i, indmin =-1; double lemin;

if (d > 0){

lemin = t[0];indmin = 0;for (i=1; i<d; i++)

if (t[i] < lemin){

lemin = t[i];indmin = i;

}}

return (indmin);}

Tableau de réels positifs

Page 76: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 76/122

Recherche séquentielle

int getval(double t[], int d, double val){

int i;

for (i=0; i<d; i++)if (t[i] = = val) /*premier trouvé*/

return(i);

return (-1); /* élément non trouvé */}

Rechercher la position d'un élément donné dans un tableau non trié :L'élément recherché peut ne pas être dans le tableauProblème en cas d'occurrence multiples de l'élément recherché

Recherche exhaustive : les éléments sont parcourus jusqu'à trouver l'élément

Temps passé : en moyenne, de dim/2 pour un tableau trié à dim pour un non trié et/ou des éléments inexistants

Page 77: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 77/122

Recherche dichotomique

int getvald(double t[], int dim, double val){

int d=0, f=dim, m;

while (f>d){

m = (d+f)/2;if (val > t[m]) /*demi tableau de droite*/

d = m;elseif (val < t[m]) /*demi tableau de gauche*/

f = m;else return (m); /*élément trouvé*/

}

return (-1); /* élément non trouvé */}

Pour un tableau trié on réduit la recherche à log(d)+1

En cas d'occurrences multiples, on ne renvoie pas nécessairement la première ou la dernière

m fd

d m f

Étape i

Étape i+1

Page 78: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 78/122

Tri à bulle

tribulle

Données : T tableau d'entiersRésultats : T : tableau trié

tant que fini=0

fini =1;pour j de 0 à N-1 faire

si T[j+1]<T[j]fini = 0;permuter T[j+1] et T[j];

fin sifin pour

fin tant que

fin tribulle

Tri par ordre croissant d'une suite Contrainte : on ne peut permuter que 2 valeur contigüe dans la suite Rarement efficace sauf quand le tableu est faiblement désordonné

N-10

Remonter le max

Page 79: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 79/122

Tri à bulle amélioré

tribulle

Données : T tableau d'entiersRésultats : T : tableau trié

tant que fini=0pour i de N-1 à 1

fini =1;pour j de 0 à i-1 faire

si T[j+1]<T[j]fini = 0;permuter T[j+1] et T[j];

fin sifin pour

fin pourfin tant que

fin tribulle

La boucle la plus profonde travaille que le tableau non encore trié

N-10

Remonter le max dans le sous tableaui-1

On peut peut prévoir une condition d'arrêt lorsque plus aucune permutation n'a lieu

Page 80: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 80/122

Tri par sélection et permutation

triselect

Données : T tableau d'entiersRésultats : T : tableau trié

pour i de 0 à N-1 fairechercher le_min sur T[i+1 à N-1]permuter le_min et T[i];

fin pour

fin tribulle

Le but est de déplacer chaque élément à sa position définitive. A chaque itération, le minimum (ou le maximum) est cherché

dans le tableau non trié puis placé à sa place par permutation.N-10

On peut peut prévoir une condition d'arrêt lorsque plus aucune permutation n'a lieu

Page 81: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 81/122

Tableaux à 2 dimensions Un tableau à 2 dimensions LxC

est un tableau à 1 dimension dont les éléments sont des tableaux à 1 dimension

Déclaration :

Accès au éléments :

Il peut y avoir débordement d'indice sans sortie du tableau : tab[i][C]= =tab[i+1][0]

type identificateur [L][C]

int i, j;double tab[10][20];...tab[i][j] = ...

tab[0][0] tab[0][C-1]

tab[L-1][0] tab[L-1][C-1]

tab[0][j]

tab[i][0]

Page 82: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 82/122

Initialisation d'un tableau 2D

Des valeurs peuvent être omises

Les règles d'initialisation par défaut sont les même que celles des tableaux 1D

Pas de contrôle de débordement des indices par le compilateur

Transmission en argument de fonction : la première dimension ne peut être omise

1 2 3 4 5 6 7 8 9 10 11 12

int tab[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};

void fonction(int tab[DIM1][DIM2]);

int tab[3][4] = {{1,2,3,4}{5,6,7,8}{9,10,11,12}}; Arrangement explicite

Arrangement automatique

même résultat en mémoire

void fonction(int tab[][]);void fonction(int tab[DIM1][]);

Page 83: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 83/122

Pointeurs

Page 84: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 84/122

Principes et Avantages

Le langage C offre la possibilité d'accéder aux données dans la mémoire de l'ordinateur à l'aide de pointeurs, c-à-d, à l'aide de variables pouvant contenir les adresses d'autres variables

Les pointeurs permettent d'accéder au contenu de variables déclarées dans d'autres fonctions

Les pointeurs permettent également d'écrire des programmes plus compacts et plus efficient

Les pointeurs sont souvent la seule solution raisonnable à un problème

Mais, les pointeurs mal exploités conduisent à des programmes illisibles (ex : GOTO)

Page 85: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 85/122

Définition

Un pointeur est une variable qui peut contenir l'adresse d'une autre variable

On dit d'un pointeur qui contient l'adresse d'une variable A qu'il pointe vers A

Pointeurs et noms de variables joue le même rôle : ils donnent accès à un emplacement dans la mémoire mais :

Page 86: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 86/122

Déclaration des pointeurs

Déclaration :

Exemples :

type *identificateur

int *p1; /* pointeur vers un entier */double *p2; /* pointeur vers un réel */

Type pointé

Syntaxe de déclaration des pointeurs

Nom du pointeur

Page 87: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 87/122

L'opérateur d'adressage

Opérateur « adresse de » & :

Exemples :

&var

int a;printf(``Entrez une valeur numérique : '');scanf(``%d'',&a);

Fournit l'adresse de la variable var

int a;int *p;a = 10;p = &a;

? a p

&a

?

10

10

?

Affectation de l'adresse de a à p

Page 88: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 88/122

L'opérateur d'indirection

Opérateur « contenu de » * :

Exemples :

*point Désigne le contenu de l'adresse référencée par le pointeur point

int a, b;

int *p;

a = 10;

p = &a;

b = *p;

a p

?

?

10

?

?

Affectation de l'adresse de a à p&a10

&a10

b

?

?

?

?

10 Affectation du contenu del'adresse pointé par p dans b

Page 89: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 89/122

Opérations sur les pointeurs Opérations autorisées :

addition, soustraction, incrémentation, décrémentation, comparaison

int *pa;

double *pb;

char *pc;...pa = pa +2;

pb++;

pc += 4;

sizeof(int)

sizeof(double)

L'opérateur sizeof(type) retourne la taille occupé en mémoire par la variabledont le type est donné en argument. L'unité utilisée est l'octet.

printf(``%d'', sizeof(double)); Affiche 8 pour «  8 octets »

Page 90: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 90/122

Priorité des opérateurs & et * Les opérateurs * et & ont la même priorité que les autres opérateurs unaires

(la négation !, l'incrémentation ++, la décrémentation --)

Dans une expression, les opérateurs unaires sont évalués de droite à gauche

int a, b, *p;p = &a;b = *p+1;*p = *p+10;*p += 2;++*p;(*p)++;

Le pointeur NULL : la valeur numérique 0 est utilisé pour indiquer qu'un pointeur ne pointe nulle part

int a, b;

b = b+1;a = a+10;a += 2;++a;a++;

!= *p++ : le pointeur est incrémenté

Page 91: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 91/122

Pointeurs en arguments de fonctionLe passage des arguments aux fonctions se fait toujours par valeur :les fonctions n'obtiennent que les valeurs de leurs paramètressans accéder aux variables qui les contiennent

void permuterRef(int a, int b){

int temp = a;a = b;b = temp;

}

int main(){int x=2, y=3;permuterRef(x,y);}

Pour pouvoir modifier les variables x et y de la fonction appelante,la fonction appelé a besoin de connaître l'adresse des variables

Permutation de deux valeurs par référence :x y

3

3

2

2

2

3 2

3 2

temp

2

?

2

a

2

2

3

b

3

3

2

3

3 2 2 3 3

Page 92: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 92/122

Pointeurs en arguments de fonctionPassage par Adresses :les adresses sont copiées dans les arguments de la fonction

void permuterAdr(int *a, int *b){

int temp = *a;*a = *b;*b = temp;

}

int main(){int x=2, y=3;permuterRef(&x, &y);return(0);}

Ce sont les variables x et y qui sont échangéespar leurs adresses rangées dans a et b

Permutation de deux valeurs par adresses :x y

3

3

2

2

2

2 3

2 3

temp

2

?

2

*a

2

2

3

*b

3

3

2

3

3 3 2 3 3

Page 93: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 93/122

Tableaux et pointeurs Les opérations sur les tableaux peuvent aussi s'effectuer avec des pointeurs :

Il existe une relation étroite entre les pointeurs et les tableaux.

Un identificateur de tableau (son nom) est en fait un pointeur constant sur le premier élément du tableau

printf(``%d'', sizeof(double));

Exemple :

&tab[0] tab

tabtab+1tab+itab[0]tab[i]

&tab[0]&tab[1]&tab[i]*tab*(tab+i)

int tab[10];int *p;p = tab; p = &tab[0];

p tab

Page 94: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 94/122

Tableaux et pointeurs (Formalisme) Il reste une différence importante entre un pointeur et un nom de tableau :

Le pointeur est une variableLe nom d'un tableau est une constante ie pointeur constant

Exemple : Copie d'un tableau

p=tab;p++;

tab =p;tab++

void tabcopy(int t1[], int t2[], int dim){

int i;for(i=0; i<dim; i++)

t1[i] =t2[i];}

void tabcopy(int t1[], int t2[], int dim){

int i;for(i=0; i<dim; i++)

*(t1+i) =*(t2+i);}

Page 95: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 95/122

Tableaux en argument de fonctionsvoid tabcopy(int t1[], int t2[], int dim){

...t1[i] =t2[i];*(t1+i) =*(t2+i);t1++;

...}

void tabcopy(int *t1, int *t2, int dim){

...t1[i] =t2[i];*(t1+i) =*(t2+i);t1++;

...}

Pointeur constant

Variable pointeur

void tabcopy(int *t1, int *t2, int dim){

while(t1<t1+dim)*t1++ = *t2++;

}

Les pointeurs ont « simplifié »les choses

Page 96: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 96/122

Chaînes de caractères

Page 97: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 97/122

Déclaration

Une chaîne de caractères se termine toujours par le caractère de fin de chaîne : \0

Taille des tableaux de caractères : N caractères + '\0' == N+1

Pas de contrôle par le compilateur

Les constantes de type chaîne de caractères sont notées entre guillemet : ''...''

'c' 'a' 'r' 'a' 'c' 't' 'e' 'r' 'e' 0char nom[10];char prenom[20];char adresse[200];

''une chaîne de caractères''''première ligne \n deuxième \'' ligne \n troisième \\n ligne''

Une chaîne de caractères est un tableau de caractère

nom[0]

Code ASCII des caractères

Caractère null : '\0'

Exemple de déclaration :

nom[1] nom[i]

première lignedeuxième '' lignetroisième \n ligne

Page 98: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 98/122

Initialisation des chaînes

char maChaine[] = {'C','o','u','c','o','u','\0'};char nom[7] = {'D','u','p','o','n','t','\0'};char prenom[] = ''Jean'';

'H'

Réservation automatique, '\0' inclut

Exemples d'initialisation :

Erreur à la compilationchar maChaine[5] = ''Coucou'';char maChaine[6] = ''Coucou'';

Erreur à l'exécution

''H''

Caractère « H » prend 1 octet en mémoire

Chaîne « H » ie tableau de 2 caractère H+\0, prend 2 octets

Page 99: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 99/122

Précédence alphabétique et lexicographique

if (c >= 'A' && c<= 'Z') c = c – 'A'+'a';if (c >= 'A' && c<= 'Z') c = c – 'a'+'A';

Relation de précédence :

'0' < 'z'

Majuscules vers minuscules

Minuscules vers majuscules

...0 1 2 3 ... 9 ... A B C ... Z ... a b c ... z...

chiffre majuscules minuscule0 est inférieur à z car le code ASCII de0 est inférieur à celui de z

Conversion :

''ABC'' précède ''DEF'' car 'A' < 'D'''ABC'' précède ''B'' car 'A' < 'B'''Abc'' précède ''abc'' car 'A' < 'a'''ab'' précède ''abcd'' car '' '' précède ''cd'''' ab'' précède ''ab'' car ' ' < 'a'

La fonction strcmp() permet d'obtenir la précédence entre deux chaînes

Page 100: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 100/122

Traitement Longueur d'une chaîne :

int lg(const char *s){

char *p=s;while(*p++);return p-s-1;

}

int lg(const char *s){

int i, n=0;for(i=0; s[i]!='\0'; i++)

n++;return n;

} int lg(const char *s){

int i, n=0;for(i=0; s[i]!='\0'; i++);return i;

}

Page 101: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 101/122

Traitement

void copie(char *d, const char *s){

int i;for (i=0; s[i]!='\0'; i++)

d[i] = s[i];}

Copie d'une chaîne :

void copie(char *d, const char *s){

while( (*d = *s)!='\0' ){

d++; s++;

}}

void copie(char *d, const char *s){

int i=0;while((d[i] = s[i])!='\0') i++;

}

void copie(char *d, const char *s){

int i=0;while( (*(d+i) = *(s+i))!='\0' ) i++;

}

void copie(char *d, const char *s){

while( *d++ = *s++);

}

Page 102: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 102/122

Librairies de Traitement

stdio.h:printf(const char *,...);scanf(char *,...);puts(const char *,...);gets(char *,...);

string.h :int strlen(const char *); /*taille d'une chaîne*/strcpy(char *, const char *); /*copie d'une chaîne*/strcat(char *, const char *); /*ajout 2 chaîne*/strcmp(char *, const char *); /*compare 2 chaînes: != <- ou >+ ; == 0 */strncpy(char *, const char *, int);/*copie n elem d'une chaîne */strncmp(char *, const char *, int);/*compare n elem d'une chaîne */int atoi(const char *); /*conversion caractère vers entier*/int atol(const char *); /*conversion caractère vers entier long*/int atof(const char *); /*conversion caractère vers réel*/

Page 103: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 103/122

Tableaux de chaînes de caractère Déclaration et initialisation :

'J' 'a' 'n' 'v' 'i' 'e' 'r' F' v' r' 'i' 'e' 'r'

'M' 'a' 'r' 's' 'A' 'v' 'i' 'M' 'a' i' 'J' u' 'i' n' 'J' 'u' 'i' 'e' t' 'A' o' u' t' 'S' e' 'p' 't' 'e' 'm' 'b' 'r' 'e''O' 'c' 't' 'o' 'b' 'r' 'e' 'N' 'o' 'v' 'e' 'm' 'b' 'r' 'e' 'D' 'c' 'e' 'm' 'b' 'r' 'e'

'\0''é' '\0'

'\0''l' '\0''\0'

'\0''l' 'l' '\0'

'\0''\0'

'\0''\0'

'é' '\0'

char mois[12][10] = {''Janvier'', ''Février'', ''Mars'', ''Avril'', ''Mai'', ''Juin'', ''Juillet'', ''Aout'', ''Septembre'', ''Octobre'', ''Novembre'', ''Décembre ''};

mois:mois[1]

Pointeur constant

mois[1] = ''Février'';

strcpy(mois[1], ''Février'');printf(''2ème mois : %s'', mois[1]);

Page 104: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 104/122

Pointeurs sur chaînes de caractère Déclaration et initialisation :

char m[] = ''Février'';char *p = ''Février'';

Modification :

pa = ''Janvier'';pb = ''Février'';pa = pb;

'F' 'v' 'r' 'i' 'e' 'r' 0'é''F' 'v' 'r' 'i' 'e' 'r' 0'é'

m

p:La chaîne est constante, on ne doit pas la modifier

On peut modifier la chaîne

Affectation :char *p;p = ''Février'';

'J' 'a' 'n' 'v' 'i' 'e' 'r' 0

'F' 'v' 'r' 'i' 'e' 'r' 0'é'pa:

pb:

L'affectation à causé la perte de la chaîne pointé par paMais elle reste allouer : fuite de mémoire

Page 105: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 105/122

Gestion dynamique de la mémoire

Page 106: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 106/122

Classes de données

3 classes de données :

Statiques :Occupent un emplacement parfaitement défini dès la compilation

Ne permettent pas de définir des tableaux de dimension variableNe se prêtent pas à la mise en œuvre de structures de données dont les tailles ne sont pas connues à la compilation

Automatiques :Créées et détruites au fur et à mesure de l'exécution du programmeet de façon transparente pour le programmeur

Dynamiques :Créés et détruites au fur et à mesure de l'exécution du programmepar le programmeur

Permettent d'allouer de la mémoire au fur et à mesure des besoins

Page 107: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 107/122

p: ?

p: 10

p:

Allocation mémoire

La fonction malloc() :demande au système d'exploitation une certaine quantité de mémoire

Prototype (défini dans <malloc.h>) :

Exemples : Allocation d'un entier

void *malloc(unsigned long int);Pointeur génériqueretourne l'adresse du bloc mémoire alloué Fonction d'allocation mémoire

Taille à allouer, en octets

int *p;p = (int *)malloc(sizeof(int));printf(''saisir un entier :'');scanf(''%d'',p);printf(''p=%d'',*p);

Page 108: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 108/122

Allocation des tableaux#include <malloc.h>#include <stdio.h>

double *newtab(double *t, int dim){

double *t;t = (double )malloc(dim*sizeof(double));if (t==NULL)

printf(''allocation impossible'');return t;

}

int main(){

double *tab=NULL;int i;tab = newtab(tab,100);if(!tab) return 1;raztab(tab,100);return 0;

}

Fuite de mémoire

Préférable

Expression non constante

Page 109: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 109/122

Libération mémoire

La fonction free() :restitue au système d'exploitation une quantité de mémoire allouée

Prototype (défini dans <malloc.h>) :

void free(void *);adresse du bloc mémoire à libérer

Fonction de libération mémoire

Page 110: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 110/122

Concaténation de deux chaînes#include <malloc.h>

int lg(const char *s){

char *p=s;while(*p++);return p-s-1;

}

char *concat(char *s1, char *s2){

char *p, *s;int lg1=lg(s1), lg2=lg(s2);

s = p = (char *)malloc(lg1+lg2+1);if(s) {

while (*p++ = *s1++);p--;while (*p++ = *s2++);free(s1);

}return s;

}

La chaîne va être redimensionnée

\0

int main(){

char *s1, *s2;...s1 = concat(s1,s2);...free(s1);free(s2);...return 0;

}

Page 111: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 111/122

Structures et Listes Chaînées

Page 112: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 112/122

StructuresLes structures permettent de désigner sous un seul nomun ensemble de valeurs pouvant être de types différents

struct fiche {

char nom[10];char prenom[20];int tel;

}

int main(){

struct fiche f1, f2 = {''Dupont'',''Jean'',0123456789};

f1.tel = 0123456789;strcpy(f1.nom, ''Dupont'');printf(''Nom = %s \n'', f1.nom);

return(0);}

définition

déclaration

initialisation

utilisation

Page 113: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 113/122

Redéfinition de typestypedef struct date{

int jour, mois, annee;}DATE;

typedef struct fiche {

char nom[10];char prenom[20];int tel;DATE d;

}FICHE;

int main(){

FICHE f1 = {''Dupont'',''Jean'',0123456789, {24,9,2008}};printf(''Jour = %d, mois = %d, année = %d \n'', f1.d.jour, f1.d.mois, f1.d.anne,);return(0);

}

Page 114: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 114/122

Structures en argument de fonctions

typedef struct date{

int jour, mois, annee;}DATE;

void saisir_date(DATE *d){

printf(''entrer le jour : \n''); scanf(''%d,&d->jour);printf(''entrer le mois : \n''); scanf(''%d,&d->mois);printf(''entrer l'année : \n''); scanf(''%d,&(*d).annee);

}

int main(){

DATE d1;saisir_date(&d1);...return(0);

}

Les structures sont transmises par valeur: il faut donc utiliserle passage par adresse pour modifier le contenu d'une structure

int main(){

DATE *d1;d1 = (DATE *)malloc(sizeof(DATE));if (d1==NULL)

return(1);saisir_date(d1);return(0);

}

&d->jour

Adresse de la structure

Champ jour de la structure

Adresse duchamp jour de

la structure

d->jour

(*d).jour

Page 115: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 115/122

Listes chaînées

Assemblage de type structure :

typedef struct fiche {

char nom[10];char prenom[20];int tel;struct fiche *pSuivant;

}FICHE;

............

1er élément 2ème élément dernier élément

Pointeurde la liste

Données de l'élément

Pointeur vers « l'élément suivant »

Définition d'un élément d'une liste :

Pointeur nul

Données de la structure

Pointeur sur une structure de type struct fiche

Le type redéfini FICHE n'existe pas encore !

Page 116: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 116/122

Insertion en début de liste

FICHE *ajout_deb(FICHE *deb_liste){

FICHE *pf = (FICHE*)malloc(sizeof(FICHE));saisir_fiche(pf);pf->pSuivant = deb_liste;return pf;

}

int main(){

FICHE *pListe = NULL;...pListe = ajout_deb(pListe);...

}

............

Pointeurde la liste

Nouvel élément

(1)

(2a)

(2b)

Page 117: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 117/122

Insertion en fin de liste

FICHE *ajout_fin(FICHE *deb_liste){

FICHE *ptr = deb_liste;FICHE *pf = (FICHE*)malloc(sizeof(FICHE));saisir_fiche(pf);

if(!deb_list)deb_liste = pf;

else{

while(ptr->pSuivant!=NULL)ptr = ptr->pSuivant;

ptr->pSuivant =pf;}return deb_liste;

}

............

Pointeurde la liste

Nouvel élément

(1)

(2)

for(ptr = deb_liste; !ptr->pSuivant; ptr = ptr->pSuivant);

Page 118: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 118/122

Parcourir une liste

void print_fiche(FICHE *pf){

printf(''Nom : %s \n, pf->nom);printf(''Prenom : %s \n, pf->prenom);printf(''Tel : %d \n, pf->tel);

}

void print_liste(FICHE *deb_liste){

FICHE *ptr = deb_liste;

while(ptr){

print_fiche(ptr);ptr = ptr->pSuivant;

}}

............

Pointeurde la liste

for(ptr = deb_liste; !ptr; ptr = ptr->pSuivant)print_fiche(ptr);

Page 119: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 119/122

Rechercher dans une liste

FICHE *chercher_tel(FICHE *deb_liste, int tel){

FICHE *ptr = deb_liste;

while(ptr && ptr->tel!=tel)ptr = ptr->pSuivant;

return ptr;}

FICHE *chercher_nom(FICHE *deb_liste, char* nom){

FICHE *ptr = deb_liste;

while(ptr && strcmp(ptr->nom, nom))ptr = ptr->pSuivant;

return ptr;}

............

Pointeurde la liste

Retourne 0 si les chaînes sont identiques

Si ptr est nul, la 2ème condition n'est pas testée.Attention à l'ordre des tests : NULL->tel est indéterminé (erreur à l'exécution).

La fonction retourne 0 en cas d'échec

Page 120: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 120/122

Suppression d'un élément

............

Pointeurde la liste

(1)

(2)

En début de liste

............

Pointeurde la liste

(2)

(1)

............

Pointeurde la liste

(1)

(2)

En milieu de liste

En fin de liste

Page 121: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 121/122

Fonction suppression

FICHE *supprimer_fiche(FICHE *deb_liste, char* nom){

FICHE *ptr = deb_liste, *p = deb_liste;

while(ptr && strcmp(ptr->nom, nom)) /*recherche de l'élément*/{

ptr = p; /*sauvegarde du précédent*/ptr = ptr->pSuivant; /*passage au suivant*/

}

if (p = = NULL) /*élément non trouvé*/return deb_liste; /*on retourne la liste*/

if (p = = deb_liste) /* en début de liste*/deb_liste = p->pSuivant;

else /*en milieu ou fin de liste*/ptr->pSuivant = p->pSuivant;

free(p); /*libération de mémoire*/return deb_liste; /*nouveau pointeur de la liste*/

}

Page 122: Notions de Programmation en C - isir.upmc.fr · Ludovic SIMON ESE Notions de Programmation en Langage C 1/122 Notions de Programmation en C Ludovic SIMON ESE, LCPC L3 : LE315 Resp

Ludovic SIMONESE

Notions de Programmation en

Langage C 122/122

Fin du Cours

Contact : [email protected]