Here is your code, with a few changes. The changes are almost entirely to do with style.
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
x = getchar();
if (x == 1) {
printf("yes\n"); /* I added some newline characters.. */
} else if (x == 2) {
printf("no\n");
} else {
printf("You must choose either yes or no\n");
}
return 0;
}
First of all, you had you had no need to put brackets around your printf statements. You had this:
Code:
if (x == 1)(printf("yes"));
I changed it to this:
Code:
if (x == 1) {
printf("yes\n");
}
Now what I have showed you is known as K&R style, which is the style used in the book, The C Programming Language by Brian Kernighan, and Dennis Ritchie. There are other styles you could use, but one thing is important - pick a style and stick to it. It makes your code easier to read and comprehend. Theoretically you could invent your own style - but at this stage of the game, with the experience you have, I would just use someone else's style, and concentrate on learning how to program. As for the style you have used, believe me, it is hard to read.
A minor issue:
You really should return an integer there. Something like:
Finally, the problem with your code not printing what you want is that you are comparing a '1' to a 1. '1' actually evaluates as 49. You can verify this by doing
Code:
printf("x = %d\n, x);
somewhere in your code after the call to getchar. Then run the program and enter a 1, and see what you get. Have a look at this to see what I am talking about.