edited by
3,457 views
1 votes
1 votes

How many times will the following loop be executed if the input data item is $01234 $?

while(c=getchar()!=0)
{
                          
}
  1. Infinitely
  2. Never
  3. Once
  4. 5 times
edited by

2 Answers

0 votes
0 votes

Infinitely(endless loop).

Because of the C Operator Precedence table !=(Not equal to) has higher precedence than =(assignment) [http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm]. So the while condition actually is: 

while( c = ( getchar() != 0 ) ) 

{

}

This doesn't give output of getchar to c variable to compare it with 0. If we print the output by using 

   int c; 
   while(c=getchar()!=0) 
   { 
    printf("%d",c);    
   }

Then for any input(eg. 0,1,01234,hi,etc.) we will always get 111... being printed continuously till we reach the output limit. If we do not give any input then it will run endlessly. I am unable to figure out why it is giving only one. Maybe you can help me there.

NOTE: Variable 'c' must not be of type char and lower size than char to avoid anomalies. See Common Mistake section at: https://en.wikibooks.org/wiki/C_Programming/stdio.h/getchar

0 votes
0 votes
A) INFINITE
It will run Infinitely .
Due to the precidence != over = the condition will be c=(getchar()!=0) .
Read about getchar() function .
It will return ASCII of the character that it just read. So no character has the ASCII value of 0 except NULL. Thus it cant terminate . Even when it reaches the End of File , the EOF will be returned by the getchar() function.
if you print the the variable c then will be 11111111111111111....... the variable c gets the value as 1 because the condition  (getchar()!=0) is true every time .. and as we know true conditions are denoted by 1 as for integers.

Hope this makes everything clear. :)
edited by

Related questions

1 votes
1 votes
0 answers
1
RahulVerma3 asked 5 days ago
68 views
My question is that can we use command line arguments without use of main function's parameters argc and *argv?
0 votes
0 votes
0 answers
2
RahulVerma3 asked Mar 16
102 views
I have a question that can we use command line arguments without main function arguments?int main(int argc, char argv){}
0 votes
0 votes
1 answer
3
SSR17 asked Feb 29
204 views
#include <stdio.h int main() { int i = -1; int x = (unsigned char)i; printf("%d", x); return 0; }output is 255 , but please explain how