DEV/BUT1/CONTROLE/DEV1.1/CM3/exo2/exo2.c

47 lines
1.3 KiB
C
Raw Permalink Normal View History

2024-02-01 13:55:03 +01:00
#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;
}