The posted code has undefined behaviour because ch
is of type int
and the format specifier %c
must match a char
.
When I replaced the conversion specifier %d it works fine.
When you switch to %d
the scanf()
fails, because Y
or y
is not an int
, so no input is consumed (apart from leading whitespace which discards the new line character on subsequent iterations of the loop) and the subsequent ch = getchar()
actually reads the user entered character, and the code works by fluke. Always check the return value of scanf()
, which returns the number of assignments made.