Ajout des TP
This commit is contained in:
47
BUT1/CONTROLE/CM3/exo2/exo2.c
Normal file
47
BUT1/CONTROLE/CM3/exo2/exo2.c
Normal file
@@ -0,0 +1,47 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
/* Fonction récursive pour trouver le maximum entre deux entiers*/
|
||||
int maxRecursif(int a, int b) {
|
||||
return (a > b) ? a : b;
|
||||
}
|
||||
|
||||
/* Fonction récursive pour trouver le maximum dans un tableau d'entiers*/
|
||||
int maxTableauRecursif(int tableau[], int taille) {
|
||||
if (taille == 1) {
|
||||
return tableau[0];
|
||||
}
|
||||
|
||||
return maxRecursif(tableau[taille - 1], maxTableauRecursif(tableau, taille - 1));
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
int i,max;
|
||||
int* entiers;
|
||||
if (argc < 2) {
|
||||
perror("Usage: ./a.out <entier1> <entier2> <entierN>\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
/* Allouer de la mémoire pour stocker les entiers fournis en ligne de commande*/
|
||||
entiers = (int*)malloc((argc - 1) * sizeof(int));
|
||||
|
||||
if (entiers == NULL) {
|
||||
perror("Erreur d'allocation mémoire");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
/* Convertir les arguments en entiers et les stocker dans le tableau*/
|
||||
for (i = 1; i < argc; i++) {
|
||||
entiers[i - 1] = atoi(argv[i]);
|
||||
}
|
||||
|
||||
/* Trouver et afficher le plus grand entier récursivement*/
|
||||
max = maxTableauRecursif(entiers, argc - 1);
|
||||
printf("%d\n", max);
|
||||
|
||||
/* Libérer la mémoire allouée pour le tableau*/
|
||||
free(entiers);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
Reference in New Issue
Block a user