+ 1

C Sharp :: Condition in loop is valid? A bit strange to me?

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { int number = 0; int counter = 0; while (counter <= 2) { number++; Console.WriteLine("loop numbvar++ post increment : " + number); Console.WriteLine("loop counter++ post increment: " + counter); counter++; if (counter == 3) // Question: why is this condition true? the loop shall work until <=2 is true.... { Console.WriteLine("Counter is : " + counter); } } // Console.ReadKey(); } } }

25th Jun 2018, 2:26 PM
Robert
1 Réponse
+ 2
The while statement reads as 'while the counter is less than or equals 2 then do what is inside the code block.' Please remember that the code inside the while code block doesn't stop running if the counter reaches 3, which will cause the while conditional statement to evaluate as false in this case, it continues until every statement is completed then loops back to the beginning where it evaluates the conditional statement again. If the counter is at 3 then the statement evaluates to false thus breaking the loop.
25th Jun 2018, 5:33 PM
ODLNT
ODLNT - avatar