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.
Can anyone help me?
Thank you in advance 😀
>Solution :
Calculating all results in every case is kind of useless. The variables containing the results are quite useless aswell because you could make the calculation in the printf function, like this:
printf("Result = %i\n\n", x+y);
lastly you could change the if statements to a switch case which would make the code look a bit cleaner, performance wise the switch case part wouldn’t have any impact, but the other changes will.
And like Weather Vane commented, you can just do while(1).