Question about for and while loop

Oct 9 2011 5:08 AM
Hello dear mates!

I am beginner at programming and have some doubts about loops. Okay, here goes little program:

private void button4_Click(object sender, EventArgs e)
{
int count = 0;

while (count < 10)
{
count = count + 1;
}

for (int i = 0; i < 5; i++)
{
count = count - 1;
}

MessageBox.Show("The answer is " + count);
}

Now here is the problem. I can not figure out why is the final result of this program 5? I have tested the while loop only to see what it will print out and it was only a number of 10. Why it did not print all numbers from 1 to 9 because count is 0 and there is condition that after every loop value increases by one until count is less than 10?

After that I have only tested for loop and its result was -5 and I really do not know why. Can someone enlighten me? 

Final result of this program is 5 probably because the result of while loop which is 10 and the result of for loop which is -5 are subtracted. Why are they subtracted? Where is that part in the program? 

Thank you mates in advanced!



Answers (4)