One of those trick questions

  • Thread starter Thread starter Michael C
  • Start date Start date
M

Michael C

without running it what will this code do. It compiles correctly.

private void X()
{
int i = 0;
{
i++;
MessageBox.Show(i.ToString());
} while(i < 10);
MessageBox.Show("Done");
}
 
Hello,
The loop should look like as follows:

do
{
i++;
MessageBox.Show(i.ToString());
}while(i < 10);

OR:

while(i < 10)
{
i++;
MessageBox.Show(i.ToString());
}

HTH. Cheers
Maqsood Ahmed [MCP,C#]
Kolachi Advanced Technologies
http://www.kolachi.net
 
OK as a guess without compiling...
i is set to 0.
i is incremented to 1.
Message box shown with "1".
while loop counts to 9.
Message box shown with "Done".
 
Hello,
No, MessageBox will show 1, then application will freeze as 'i' never
gets incremented after the while statement (there is a semi-colon after
'while' and 'do' is absent). And it'll never display "Done" :)
Bye!!

Maqsood Ahmed [MCP,C#]
Kolachi Advanced Technologies
http://www.kolachi.net
 
without running it what will this code do. It compiles correctly.

private void X()
{
int i = 0;
{
i++;
MessageBox.Show(i.ToString());
} while(i < 10);
MessageBox.Show("Done");
}

Without compiling and running, my guess is

i gets set to 0
i gets incremented to 1
A message box is displayed showing 1
i < 10 gets evaluated to true, but since you close the loop immediately
with a semicolon, there is no behavioral impact
A message box is displayed showing Done

For a while loop, the loop code follows while. You could also use
do...while, in which case the do goes at the beginning.
 
Tom Porterfield said:
Without compiling and running, my guess is

i gets set to 0
i gets incremented to 1
A message box is displayed showing 1
i < 10 gets evaluated to true, but since you close the loop immediately
with a semicolon, there is no behavioral impact
A message box is displayed showing Done

Not at all, the while loop never ends as i is never incremented, you just
peg the CPU in an endless loop.

Willy.
 
Back
Top