I'm teaching myself C. My background is Java. I'm writing a simple console app that is supposed to prompt the user for a number, and then tell the user what number he printed, and then prompt him for another number. The program exits if the user types in 0.
My code is not behaving the way I expect it to. This is the code:
#include <stdio.h>
int main() {
while (1) {
printf("Please enter a number: ");
int this_is_a_number = 0;
scanf("%d", &this_is_a_number);
printf("You entered %d\n", this_is_a_number);
if (this_is_a_number == 0) {
break;
}
getchar();
}
return 0;
}
When the program starts, it doesn't prompt me for a number. It does let me type one in. After hitting return, it lets me type in another, and so on and so forth until I return 0. Then it prints out everything that it was supposed to print out earlier, and then exits.
So for example, if I start the program and then type 7
, 8
, 9
, and 0
, hitting return after each one, the console should look like this:
Please enter a number:
7
You entered 7
Please enter a number:
8
You entered 8
Please enter a number:
9
You entered 9
Please enter a number:
0
You entered 0
But instead, it looks like this:
7
8
9
0
Please enter a number:
You entered 7
Please enter a number:
You entered 8
Please enter a number:
You entered 9
Please enter a number:
You entered 0
What am I not understanding about flow in C?