This program runs into an infinite loop despite providing ‘n’ as an input,to exit the while loop.
What could be the issue ?
#include<stdio.h>
main()
{
int num,p=0,q=0,r=0;
char check='y';
while(check!='n')
{
printf("do you want to enter a number y or n");
scanf("%c",&check);
getchar();
printf("enter a number");
scanf("%d",&num);
if(num>0)
p++;
else if(num<0)
q++;
else
r++;
}
printf("positive=%d\t negative=%d\t zero=%d\t",p,q,r);
}
The
scanf("%d", &num);leaves the newline in the input buffer, thus in the next iteration of the loop, that is stored incheck. After that, thegetchar()consumes the'n'or'y'you entered. Then thescanf("%d", &num);skips the newline left in the buffer, scans the entered number, and leaves the newline in the buffer. You need to remove the newline between scanning in the number and querying whether you want a next iteration.Above that, it would be better to exit the loop immediately after the user entered an
'n', sowould be better. That would still be open to bad things should the user input not match expectations, so if you want a robust programme, you need to check the return value of
scanfto know whether the conversion was successful, and completely empty the input buffer before and after scanning in the number.