+ 4

Loops regarding increment (overthinking !! resulted to doubt)

So the code ; 1)code int num = 1; while(num < 6) { Console.WriteLine(num); num+=2; } Displays 1,3 and 5 and also compare to this code; 2)code int num = 0; while(num++ < 6) Console.WriteLine(num); Which results 6 answers in total.. So my question is that why the first code displays only upto 5..cause once it becomes 3 and goes again on the loop it passes the while and gets checked for less than 6 and then thus results 5..so why doesn't it result something 7 after that..cause it goes again to the loop once the answer is 5,to check weather there satisfied or not..cause it meets the while statement first so why doesn't it also result 7 been displayed..... And then if that happened in code 1 then why does this happens in code 2..I mean why does that executes for 6 times..but not the first code.. I mean anyhow to complete the code it has to go pass the while..so why doesn't the 1st code results number 7 ? Hope u understand my silly question 😁🤟

7th Feb 2023, 11:09 AM
•Đคяк รтяεคм 𝅘𝅥𝅮 ᴺ•ᵀ•ᴬˢᵘʳᵃᵖᵖᵘˡᶦ
•Đคяк รтяεคм 𝅘𝅥𝅮 ᴺ•ᵀ•ᴬˢᵘʳᵃᵖᵖᵘˡᶦ - avatar
3 Respostas
+ 4
I cannot understand your question very well to be honest, but it seems that you are asking for clarification on when the loops stop. Let's look at how the increments work first. Both num+=2 and num++ have the value of num increased AFTER the execution of the statement. For your first code, the increment statement is the last statement in the code block, thus it is increased BEFORE the next round (iteration) and get checked again. When it was 5, then 5+=2 became 7, and then entered next round and get checked. 7 < 6 == false, so the loop stopped and nothing more was output. Hence the last output 5. For the second, the increment and checking is in the same statement. Since it is increased AFTER the statement, so the checking was 5 < 6 == true. And num became 6 after the check statement and got written to the console as 6. When it entered the next round, num was already 6, 6 < 6 == false and thus the loop stopped. Hence the last output 6.
7th Feb 2023, 11:56 AM
Lochard
Lochard - avatar
+ 3
Lochard Thank you buddy 😁✌️
7th Feb 2023, 4:55 PM
•Đคяк รтяεคм 𝅘𝅥𝅮 ᴺ•ᵀ•ᴬˢᵘʳᵃᵖᵖᵘˡᶦ
•Đคяк รтяεคм 𝅘𝅥𝅮 ᴺ•ᵀ•ᴬˢᵘʳᵃᵖᵖᵘˡᶦ - avatar
+ 2
... num+=5 // num == 3 // end of round, num == 5 } // next round, num == 5 while (num < 6) // num == 5 { Console.WriteLine(num); // num == 5 num+=2; // num == 5 } while (num < 6) // num == 7 // stopped, num == 7 if not destroyed ... Console.WriteLine(num); // num == 5 while (num++ < 6) // num == 5 Console.WriteLine(num); // num == 6 while (num++ < 6) // nim == 6 // stopped, num == 6 if not destroyed
7th Feb 2023, 12:05 PM
Lochard
Lochard - avatar