TP4: Add the famous palindrome TP example
[Algorithmic_C.git] / TP4 / palindrome.c
diff --git a/TP4/palindrome.c b/TP4/palindrome.c
new file mode 100644 (file)
index 0000000..a84c08f
--- /dev/null
@@ -0,0 +1,42 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <stdbool.h>
+#include <string.h>
+
+#define LEN_MAX 40
+
+bool palindrome_iter(char* mot, int longeur) {
+    int i = 0;
+    int j = longeur - 1;
+
+    while (i <= j) {
+        if (mot[i] != mot[j]) { return false; }        
+        i++;
+        j--;
+    }
+    return true;
+}
+
+bool palindrome_rec_aux(char* mot, int i, int j) {
+    if (i >= j) { return true; }
+    if (mot[i] != mot[j]) { return false; }
+    return palindrome_rec_aux(mot, i+1, j-1);
+}
+
+bool palindrome_rec(char* mot, int longueur) {
+    return palindrome_rec_aux(mot, 0, longueur-1);
+}
+
+
+int main() {
+    char mot[LEN_MAX];
+
+    printf("Saisir un mot\n");
+    scanf("%s", mot);
+    if (palindrome_rec(mot, strlen(mot)))
+        printf("%s est un palindrome\n", mot);
+    else
+        printf("%s n'est pas un palindrome\n", mot);
+
+    return 0;
+}