+ 1

Explain this code

How come it's an infinite loop that outputs 0 every loop? https://code.sololearn.com/cVSQ9WCtXv7C/?ref=app

5th Jan 2019, 2:52 PM
Asirap
4 Respuestas
+ 4
Here in this code, You intialized variable i with 0. Now when you want to increment it you use i=i++ which always initialize with same value 0. Because of that post increment operator which always initialize first and then do increment, so it will never increase the value of i. You can use pre increment operator like this i=++i. Or you can use i=i+1
5th Jan 2019, 3:05 PM
Raj Chhatrala
Raj Chhatrala - avatar
+ 3
There are two types of increment :- Pre-increment and Post-increment. It has a basic property that , Post increment add after one value if the variable is existing at the outside of loop. For eg:- while (i < 0) // consider i = 0 { i++;// here value of i is 0. } When it comes out of the loop, its value will be one. Pre increment will increment value by one before some process. Eg. :- while ( i < 5 ) // again consider i =0 { ++i; // here, i = 1 } And it will be accesible by all the steps. Otherwise like post increment its value will by default. Here, having two examples:- One is your code which uses by default assigned value. https://code.sololearn.com/c90QaRLuQTdy/?ref=app And other is my solution.,,, https://code.sololearn.com/c0rwOOjUR6Xb/?ref=app
5th Jan 2019, 9:10 PM
Bipin Tatkare
Bipin Tatkare - avatar
0
Raj Chhatrala☑️ i still can't understand 😓... the println line is after the postincrement line so it should print the incremented value of i... and why is that incremented value not carried forward in the next iterations of the loop?
5th Jan 2019, 4:55 PM
Asirap
0
Bipin Tatkare - (B. R. T) thanks for answering... I understand pre and post increment. My confusion was that since the println line is AFTER the i=i++ line it should print the increased value... and then why is 0 printed everytime?
6th Jan 2019, 12:06 PM
Asirap