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!
Loading
Orlando StevensonPosted Oct 9, 2011, 7:34 AM
VulpesPosted Oct 9, 2011, 6:02 AM
So, if you comment out the while loop, count which starts off at 0 will end up as -5.
My last sentence was only talking about the for loop which decrements (i.e. reduces by 1) the count variable on each of its five iterations.
Orlando StevensonPosted Oct 9, 2011, 5:57 AM
VulpesPosted Oct 9, 2011, 5:35 AM