i think my code skips the line scanf("%c", &operation); when i run the program, but when i move the scanf"%c" above the scanf"%d" it works... also when i change "%c" to "%s" it works too... here's my code...
#include <stdio.h>
main()
{
char operation;
int num1, num2, ans = 0;
printf("Enter number 1: ");
scanf("%d", &num1);
printf("Enter number 2: ");
scanf("%d", &num2);
printf("A - Addition \n");
printf("S - Subtraction \n");
printf("M - Multiplication \n");
printf("D - Division \n");
printf("Enter a character for the operation: ");
scanf("%c", &operation); // this line
switch(operation) {
case 'A':
ans = num1 + num2;
break;
case 'S':
ans = num1 - num2;
break;
case 'M':
ans = num1 * num2;
break;
case 'D':
ans = num1 / num2;
break;
default:
printf("%c is an invalid character \n", &operation);
}
printf("asnwer is %d", ans);
}
moving up scanf"%c"
#include <stdio.h>
main()
{
char operation;
int num1, num2, ans = 0;
printf("A - Addition \n");
printf("S - Subtraction \n");
printf("M - Multiplication \n");
printf("D - Division \n");
printf("Enter a character for the operation: ");
scanf("%c", &operation); // this line
printf("Enter number 1: ");
scanf("%d", &num1);
printf("Enter number 2: ");
scanf("%d", &num2);
switch(operation) {
case 'A':
ans = num1 + num2;
break;
case 'S':
ans = num1 - num2;
break;
case 'M':
ans = num1 * num2;
break;
case 'D':
ans = num1 / num2;
break;
default:
printf("%c is an invalid character \n", &operation);
}
printf("asnwer is %d", ans);
}
changing %c to %s...
#include <stdio.h>
main()
{
char operation;
int num1, num2, ans = 0;
printf("Enter number 1: ");
scanf("%d", &num1);
printf("Enter number 2: ");
scanf("%d", &num2);
printf("A - Addition \n");
printf("S - Subtraction \n");
printf("M - Multiplication \n");
printf("D - Division \n");
printf("Enter a character for the operation: ");
scanf("%s", &operation); // this line
switch(operation) {
case 'A':
ans = num1 + num2;
break;
case 'S':
ans = num1 - num2;
break;
case 'M':
ans = num1 * num2;
break;
case 'D':
ans = num1 / num2;
break;
default:
printf("%c is an invalid character \n", &operation);
}
printf("asnwer is %d", ans);
}
why my first code don't work? and why the other 2 works fine? any reason behind it?