I am learning C program. I wrote a program to create a calculator using switch statement. When I tried to run this code the program stops in the middle of it when running, I realized what the problem was, I show you my three attemps, the first one is the correct one but I woud like to know why the others two didn't work.
// Calculator
#include <stdio.h>
int main ()
{
int num1, num2;
char key;
printf("CALCULATOR \n");
printf("choose +, -, *, / or %% \n");
scanf("%c", &key);
printf("Enter two integers\n");
scanf("%d %d", &num1, &num2);
switch(key)
{
case '+': printf("%d", num1 + num2);
break;
case '-': printf("%d", num1 - num2);
break;
case '*': printf("%d", num1 * num2);
break;
case '/': printf("%d", num1/num2);
break;
case '%': printf("%d", num1%num2);
break;
default: printf("syntax error");
}
return 0;
} // the correc one
but these two are wrong, I want to know why if the logic is the same.
// Calculator
#include <stdio.h>
int main ()
{
int num1, num2;
char key;
printf("CALCULATOR \n");
printf("Enter two integers\n");
scanf("%d %d", &num1, &num2);
printf("choose +, -, *, / or %% \n");
scanf("%c", &key);
switch(key)
{
case '+': printf("%d", num1 + num2);
break;
case '-': printf("%d", num1 - num2);
break;
case '*': printf("%d", num1 * num2);
break;
case '/': printf("%d", num1/num2);
break;
case '%': printf("%d", num1%num2);
break;
default: printf("syntax error");
}
return 0;
} //wrong
the last one
// Calculator
#include <stdio.h>
int main ()
{
int num1, num2;
char key;
printf("CALCULATOR \n");
printf("Enter a integer\n");
scanf("%d", &num1);
printf("choose +, -, *, / or %% \n");
scanf("%c", &key);
printf("Enter a integer\n");
scanf("%d", &num2);
switch(key)
{
case '+': printf("%d", num1 + num2);
break;
case '-': printf("%d", num1 - num2);
break;
case '*': printf("%d", num1 * num2);
break;
case '/': printf("%d", num1/num2);
break;
case '%': printf("%d", num1%num2);
break;
default: printf("syntax error");
}
return 0;
}
I'd appreciate an answer.