| 1 | #include <stdio.h> |
| 2 | #include <stdbool.h> |
| 3 | |
| 4 | /** Display a prompt to the user then wait for an integer input. */ |
| 5 | int promptValue(const char* prompt) { |
| 6 | printf("%s:\n", prompt); |
| 7 | int result; |
| 8 | scanf("%d", &result); |
| 9 | return result; |
| 10 | } |
| 11 | |
| 12 | void displayMenuEntry(int index, const char* label) { |
| 13 | printf("%d | %s\n", index, label); |
| 14 | } |
| 15 | |
| 16 | void displayMenu() { |
| 17 | displayMenuEntry(1, "Addition"); |
| 18 | displayMenuEntry(2, "Substraction"); |
| 19 | displayMenuEntry(3, "Multiplication"); |
| 20 | displayMenuEntry(4, "XOR"); |
| 21 | displayMenuEntry(5, "Exit"); |
| 22 | } |
| 23 | |
| 24 | /** Prompt the user for his operation choice. |
| 25 | * |
| 26 | * @return The selected operation. No invalid value can be returned. |
| 27 | */ |
| 28 | int promptOperation() { |
| 29 | displayMenu(); |
| 30 | int result; |
| 31 | |
| 32 | do { |
| 33 | result = promptValue("Choose an option"); |
| 34 | |
| 35 | if (result >= 1 && result <= 5) { |
| 36 | break; |
| 37 | } |
| 38 | |
| 39 | puts("Please choose a valid option (1-5)"); |
| 40 | } while (true); |
| 41 | |
| 42 | return result; |
| 43 | } |
| 44 | |
| 45 | int main() { |
| 46 | int operation = promptOperation(); |
| 47 | |
| 48 | if (operation == 5) { |
| 49 | return 0; |
| 50 | } |
| 51 | |
| 52 | int initialValue = promptValue("Initial value"); |
| 53 | |
| 54 | do { |
| 55 | int nextValue = promptValue("Next value"); |
| 56 | |
| 57 | if (nextValue == 0) { |
| 58 | break; |
| 59 | } |
| 60 | |
| 61 | switch (operation) { |
| 62 | // Addition |
| 63 | case 1: |
| 64 | initialValue += nextValue; |
| 65 | break; |
| 66 | |
| 67 | // Substraction |
| 68 | case 2: |
| 69 | initialValue -= nextValue; |
| 70 | break; |
| 71 | |
| 72 | // Multiplication |
| 73 | case 3: |
| 74 | initialValue *= nextValue; |
| 75 | break; |
| 76 | |
| 77 | // XOR |
| 78 | case 4: |
| 79 | initialValue ^= nextValue; |
| 80 | break; |
| 81 | } |
| 82 | |
| 83 | printf("Result: %d\n", initialValue); |
| 84 | } while (true); |
| 85 | } |