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