The only way for the loop to terminate is if both a!=0
and a!=1
are false. Or in other words: it can only end when a == 0
and a == 1
at the same time. That is of course impossible, so the loop never terminates.
If you want to loop to terminate when the user inputs 1
or 0
, then you need a logical and operator there:
do
{
puts("Give 1 or 0 for input:");
scanf("%d",&a);
} while(a!=0 && a!=1);
Aside from that, you really must check the return value of scanf
, and purge the input stream in case of failure. If you input a character, then scanf
will signify it failed, but leave the character in the input stream. The subsequent iterations will just get stuck on trying to read that character.
One way to do so is with scanf
itself and the %*s
format specifier.
do
{
puts("Give 1 or 0 for input:");
int read_res = scanf(" %d",&a);
if (read_res != 1)
scanf("%*s");
} while(a != 0 && a != 1);
The asterisk in the format string means scanf
will still match any non white-space character and purge them from the stream, but will not attempt to assign them into anything (so no extra parameter is required). I also added a leading white-space to %d
in order to disregard any leading white-spaces before the number.