I'm having some trouble with 'The While Loop' | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I'm having some trouble with 'The While Loop'

So, I'm currently going through the C# tutorial still, and I came across a question on 'The While Loop' lesson that I didn't get. Here's the question: How many times will the following loop execute? int x = 1; while (x++ < 5) { if (x % 2 == 0) x+=2 } So, first off, why would the code execute in a visable way if there isn't a Console.WriteLine (num)? Second off, assuming it would execute anyways; Would the while not read x and then add 1 afterwards, since x is a postfix? Would that not make it 3 loops in total then, or am I incorrect? P.S.: This community has been super helpful so far and put up with my dumb questions, so thanks for that. I'm in love with this app frankly, so huge props to both the mods and devs that keep this running; the lessons are extremely helpful and the community is 👌

12th Mar 2019, 4:12 PM
Oliver
2 Answers
+ 3
In my opinion: first step x++ <5 as here is postfix => 1 < 5 (true), in the if conditional 1 % 2 = 1 != 0 (false). Second step 2 < 5 (true again) , if check => 2 % 2 == 0 (true) and x = 3 + 2 = 5. 5< 5 ( first condition check in while loop is false ) so that is the end. The question is how many times the loop will run => you just have to count it. You can see the code - I hope it can helps you. https://code.sololearn.com/cM4X1F8AQS3c/?ref=app
12th Mar 2019, 4:38 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 1
Looking @ whiteCat's link, if there wasn't a Console.WriteLine(), there would not be a VISIBLE way to see it, true, but why do you think we use Console.Writeline? (to have a visual control) Reasoning of TheWhiteCat is correct.
12th Mar 2019, 9:36 PM
[No Name]