+ 4

A simple but difficult for me plzz explain how come 5 as output

int i =1 ; for ( ; i<5; i++ ) { i*=i ;} System. out.print(i);

26th Apr 2017, 5:08 AM
Nadir wadsariya
Nadir wadsariya - avatar
3 Antworten
+ 3
ok first we have to learn how for loop actually works, then let's begin. for(initial condition; check condition after each itration; Manipulator counter before check condition) as you can see in first part we told that we want to set some value on the initialization of loop and it runs one time only then it execute the code written inside the for loop block. when the one itration of code block is finished it the run third part of for loop (manipulation counter section) then after it goes to the second part of for loop ( check condition) if it is true the repeat the whole process again and if it is false then jump out from loop in you case you declared int i=1; you declared and initialized variable i with value of 1 for ( ; i<5; i++) let's assume the above Loop runed to the i=4 and the next itration is about to execute. now what happens here first the i get incremented buy one, then it checks the condition so that's why the value of i is 5. i tried to keep this as easy as i can do. thank you.
26th Apr 2017, 5:31 AM
Keshave Jat
Keshave Jat - avatar
+ 9
i = 1< 5 --> 1 * 1 = 1 1++ = 2 < 5 --> 2 * 2 = 4 4++ = 5 --> for condition not met, loop exits value of i is 5
26th Apr 2017, 5:23 AM
Nikolay Nachev
Nikolay Nachev - avatar
+ 2
Okay, ri8 Thank you!!
26th Apr 2017, 5:25 AM
Nadir wadsariya
Nadir wadsariya - avatar