Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can Any body Tell me WHY???!!!! 1

Status
Not open for further replies.

maltobji

Programmer
Feb 13, 2001
31
JO
dear all,
although it may seems easy ...but can any body tell me why ,when i excute this code it enters in infinite loop when i enter the character (a)...
#include <stdio.h>

void main(void)
{
int c = 100 ;

while ( c != 'a' )
{
scanf(&quot;%d&quot;,&c ) ;

if( c%2 != 0)
printf(&quot;Odd\n&quot;);
else
printf(&quot;Even\n&quot;);
}
printf(&quot;GoodBye\n&quot;);
}
thanx in adnace ...
Mohammed Al-Tobji
Electrical Engineer
 
I believe the while loop compares the ascii value of 'a', which is 97, to the integer value of c, which is 100. Since c will never be equal to a, it loops infinitely.

Brad
 
u r trying to compare int c with a as explained by Malachi.

try changing the loop to while ('c'!='a') and see the results


 
the above solution will ensure that your printout is there. hoeever in case u want to exit the while loop, insert a break statement after displaying ODD/EVEN

 
No, No, No!!

The problem is with the scanf function:

1) you are trying to read a decimal i.e. a string of numerical characters. When you type an 'a' character, scanf does not know how to convert it to a decimal since it is expecting one or more of [0123456789], therefore it does not perform the conversion, it does not remove the character from the input stream, and it is still there the next time you call scanf. This results in an infinite loop. Fortunately, scanf returns the number of conversions made. If a successful conversion is made it should return a 1. Change the code as follows to correct the problem:

Code:
int nConv ;
nConv = scanf(&quot;%d&quot;,&c ) ;
if (nConv != 1) {
  c = getchar() ;
  fflush(stdin)
}

This should do the trick. I have encountered this same problem many times and this will work.

Brudnakm.
 
thanx alot all,
i think what brudnakm explained the problem...thanks again
Mohammed Al-Tobji
Electrical Engineer
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top