简体   繁体   中英

Possible output of the following program fragment?

for(i=getchar();; i=getchar())
if(i=='x')
break;
else putchar(i);

Answer is : mi

Can someone explain this piece of code ?(MCQ Question)

This question can be solved by eliminating incorrect answer. This fragments prints character and exits loop if the character is an x . So the program would not output an x .

Any output string that doesn't contain x is possible. In your MCQ, possibly mi is the only option with x and all other options contain x somewhere in the string making them incorrect answer.

If input is "mix....", output would be "mi". Below is your loop unrolled.

getchar() -> m -> else -> print m  /* First getchar */
getchar() -> i -> else -> print i  /* Second getchar */
getchar() -> x -> if -> break      /* Second getchar */
for(i=getchar();; i=getchar())
if(i=='x')
break;
else putchar(i);

your Code will keep on running till it encounter 'x' so whatever input you give, it will read character by character as you have used getchar() function..

  • If character is 'x' then break the loop.
  • else print character.

like, If the input is

sparx

output will be

spar

The for loop

 for(i=getchar();; i=getchar())

and syntax and structure of the for loop is

for ( variable initialization; condition; variable update )

as i = getchar() will read char 'i' it is ok. next there is no condition and final in updating you are again reading a character so it a infinite loop.

Loop will terminate only when it will encounter 'x' as the statement

if(i=='x')
break;

Otherwise it will keep on printing the character.

else putchar(i);

Here is the Demo .

Hope it helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM