Add TP 7 correction.
[TD_C.git] / TP_7_C / exo2-full.c
diff --git a/TP_7_C/exo2-full.c b/TP_7_C/exo2-full.c
new file mode 100644 (file)
index 0000000..acbe4a3
--- /dev/null
@@ -0,0 +1,85 @@
+#include <stdio.h>
+#include <stdbool.h>
+
+/** Display a prompt to the user then wait for an integer input. */
+int promptValue(const char* prompt) {
+    printf("%s:\n", prompt);
+    int result;
+    scanf("%d", &result);
+    return result;
+}
+
+void displayMenuEntry(int index, const char* label) {
+    printf("%d | %s\n", index, label);
+}
+
+void displayMenu() {
+    displayMenuEntry(1, "Addition");
+    displayMenuEntry(2, "Substraction");
+    displayMenuEntry(3, "Multiplication");
+    displayMenuEntry(4, "XOR");
+    displayMenuEntry(5, "Exit");
+}
+
+/** Prompt the user for his operation choice.
+ *
+ * @return The selected operation. No invalid value can be returned.
+ */
+int promptOperation() {
+    displayMenu();
+    int result;
+
+    do {
+        result = promptValue("Choose an option");
+
+        if (result >= 1 && result <= 5) {
+            break;
+        }
+
+        puts("Please choose a valid option (1-5)");
+    } while (true);
+
+    return result;
+}
+
+int main() {
+    int operation = promptOperation();
+
+    if (operation == 5) {
+        return 0;
+    }
+
+    int initialValue = promptValue("Initial value");
+
+    do {
+        int nextValue = promptValue("Next value");
+
+        if (nextValue == 0) {
+            break;
+        }
+
+        switch (operation) {
+        // Addition
+        case 1:
+            initialValue += nextValue;
+            break;
+
+        // Substraction
+        case 2:
+            initialValue -= nextValue;
+            break;
+
+        // Multiplication
+        case 3:
+            initialValue *= nextValue;
+            break;
+
+        // XOR
+        case 4:
+            initialValue ^= nextValue;
+            break;
+        }
+
+        printf("Result: %d\n", initialValue);
+    } while (true);
+}