Année universitaire 2003-2004

DEUG MIAS
Module Info 2
Travaux dirigés


Séance 4 :

  • Instructions Conditionnelles.

  • TD 4 : Instructions conditionnelles
    1. Considérons la suite d'instructions suivante:
    if (x>=10)
      x=6*x;
    if (x>=60)
      x=x/3;

    Si x est inférieur strictement à 10 alors x est inchangé sinon il est est multiplié par 2; on peut donc remplacer le morceau de programme ci-dessus par l'unique instruction:
    if (x>=10)
      x=2*x;

    Procéder de même dans les 3 cas suivants:
    if (x>=10)
      x=x+12;
    if (x>=22)
      x=x% 22;
     
    if (x<=10)
      x=x-5;
    if (x<=5)
      x=x-5;
     
    if (x>=10)
      x=10+x% 10;
    if (x>20)
      x=x/2;

    2. Considérons la suite d'instructions suivante:
    if (a < b)
      p=1;
    else p = 0;

    Elle peut se réécrire: p = a < b;
    Procéder de même dans les cas suivants:
    if (x == 10)
      if (x == 5)
       p=0;
      else p = 1;
    else p = 1;
    if ((x > 2) || (x < 2))
      p=0;
    else p = 1;
    if ((x > 2) && (y < 2))
      if (z == 5)
       p=1;
      else p = 0;
    else p = 0;
     
    if (x == 10)
      if (y == 5)
       p=0;
      else p = 1;
    else p = 1;
     
    if ((x > 2) || (x > 7))
      p=0;
    else p = 1;
     
    if ((x > 2) && (y < 2))
      if (z == 5)
       p=1;
      else p = 0;
    else p = 1;

    3. Réécrire l'instruction suivante avec un seul "if - else":
    if (x > 2)
      if (z == 5)
       y = 7;
      else y = 12;
    else y = 12;

    4. Réécrire l'instruction suivante avec deux "if" sans "else":
    if (x < 17)
      y = 7;
    else y = 12;

    5. Réécrire l'instruction suivante avec un "switch" et sans "if":
    if ((x == 1)|| (x == 2))
      printf("Fail\n");
    else if ((x == 3)|| (x == 4) || (x == 5))
       printf("Satisfactory\n");
      else if ((x == 6)|| (x == 7))
         printf("Good\n");
        else if (x == 8)
           printf("Great\n");

    6. Simplifier chacune des instructions suivantes:
    if (x < 60)
      if (x > 75)
       printf("%d \n", x);
      else printf("%d \n", 2*x);
    else printf("%d \n", 3*x);
     
    if (x >= 60)
      printf("%d \n",x);
    else if (x <= 50)
        printf("%d \n", 2*x);
      else if (x >= 70)
         printf("%d \n", 3*x);
        else printf("%d \n", 4*x);

    Pour les plus rapides un complèment de TD


    Commentaires pascal.lafourcade@lsv.ens-cachan.fr