TP_13 exo2: Finish the implementation of a basic tic-tac-toe game.
[TD_C.git] / TP_7 / exo2 / exo2.c
1 #include <stdio.h>
2 #include <stdbool.h>
3
4 //FIXME: Comment the code !!!
5
6 void displayMenuEntry(int num, const char* option) {
7 printf("%d - %s\n", num, option);
8 }
9
10 void displayMenu() {
11 displayMenuEntry(1, "Addition");
12 displayMenuEntry(2, "Soustraction");
13 displayMenuEntry(3, "Multiplication");
14 displayMenuEntry(4, "Division");
15 displayMenuEntry(5, "Puissance");
16 displayMenuEntry(6, "Quitter");
17 }
18
19 int promptValue(const char* invite) {
20 int value = 0;
21 puts(invite);
22 scanf("%d", &value);
23 return value;
24 }
25
26 int promptOperation() {
27 displayMenu();
28 return promptValue("Veuillez choisir une operation ?");
29 }
30
31 int doAddition(int val1, int val2) {
32 return val1 + val2;
33 }
34
35 int doSubstraction(int val1, int val2) {
36 return val1 - val2;
37 }
38
39 int doMultiplication(int val1, int val2) {
40 return val1 * val2;
41 }
42
43 int doDivision(int val1, int val2) {
44 //FIXME: Useless code path given the exit main loop condition
45 if (val2 == 0) {
46 printf("Division par zero !\n");
47 // FIXME: I'm not very fond of this convention ...
48 return 0;
49 } else {
50 return val1 / val2;
51 }
52 }
53
54 int doPuissance(int base, int expo) {
55 int power;
56 if ( expo == 1) {
57 power = base;
58 } else if ( expo % 2 == 0 ) {
59 power = doPuissance(base*base, expo/2);
60 } else {
61 power = base*doPuissance(base*base,(expo-1)/2);
62 }
63 return power;
64 }
65
66 int doOperation(int selection, int val1, int val2) {
67 int op_result;
68 switch (selection) {
69 case 1:
70 op_result = doAddition(val1, val2);
71 break;
72 case 2:
73 op_result = doSubstraction(val1, val2);
74 break;
75 case 3:
76 op_result = doMultiplication(val1, val2);
77 break;
78 case 4:
79 op_result = doDivision(val1, val2);
80 break;
81 case 5:
82 op_result = doPuissance(val1, val2);
83 break;
84 case 6:
85 break;
86 default:
87 puts("Faire un choix compris entre 1 et 6");
88 }
89 return op_result;
90 }
91
92 int main() {
93 int choice = promptOperation();
94 int value1 = promptValue("Veuillez saisir une valeur entiere initiale ?");
95 int value2 = 0, result = 0;
96 bool first_loop = true;
97
98 for (;;) {
99 if (choice == 6) break;
100 if (first_loop) {
101 value2 = promptValue("Veuillez saisir une valeur entiere avec laquelle l'operation sera effectuee ?");
102 if (value2 == 0) break;
103 result = doOperation(choice, value1, value2);
104 first_loop = false;
105 } else {
106 value2 = promptValue("Veuillez saisir la prochaine valeur entiere avec laquelle l'operation sera effectuee sur l'ancien resultat ?");
107 if (value2 == 0) break;
108 result = doOperation(choice, result, value2);
109 }
110 printf("Le resultat de l'operation choisie est %d\n\n", result);
111 }
112
113 return 0;
114 }