I'm learning some basics of C (I'm actually doing Harvard's cs50x) and I wrote this code:
#include <cs50.h>
#include <stdio.h>
int main(void) {
while(0 == 0) {
printf("1. SUM\n2. SUBSTRACTION\n3. MULTIPLICATION\n4. DIVISION\n5. QUIT\n");
int a = get_int("Choose one option: ");
if (a == 1) {
int x = get_int("x: ");
int y = get_int("y: ");
int sum = x + y;
int sub = x - y;
int division = x/y;
int mul = x*y;
printf("Result = %i\n\n", sum);
}
else if (a == 2) {
int x = get_int("x: ");
int y = get_int("y: ");
int sum = x + y;
int sub = x - y;
int division = x/y;
int mul = x*y;
printf("Result = %i\n\n", sub);
}
else if (a == 3) {
int x = get_int("x: ");
int y = get_int("y: ");
int sum = x + y;
int sub = x - y;
int division = x/y;
int mul = x*y;
printf("Result = %i\n\n", mul);
}
else if (a == 4) {
int x = get_int("x: ");
int y = get_int("y: ");
int sum = x + y;
int sub = x - y;
int division = x/y;
int mul = x*y;
printf("Result = %i\n\n", division);
}
else if (a == 5) {
printf("Alright! See you soon!\n");
break;
}
else {
printf("Invalid Input\n");
break;
}
}
}
It works exactly as I want it to, but I feel like it could be written in a better way.
I really don't like all that repetition of int variables and I think that it could be optimized someway but don't know how.