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

Answer is : mi

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

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
Abdul
  • 69
  • 3

2 Answers2

4

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 */
Gyapti Jain
  • 4,056
  • 20
  • 40
0
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!!

Blackhat002
  • 598
  • 4
  • 12