Can anyone explain for loop (init and condition)?.. and the concept of init and condition in simple way to understand.

15th Aug 2016, 10:43 AM
Zafirah Mohamed iqbal
Zafirah Mohamed iqbal - avatar
2 Answers
+ 3
init is short for inialise, so it's ran ONLY when the loop is about to begin. The condition on the other hand is like an if statement for the loop that is checked just after initialising and after every loop; if it isn't satisfied it won't run the loop (like a while-loop condition). Lastly a for-loop has a third chunk that executes at the end of each iteration and BEFORE it checks the condition again. e.g. for (int i = 0; i < 3; ++i) { std::cout << i << std::endl; } Will print: 0 1 2 i begins as 0 in the initialiser, i is less than 3 so it runs the loop. The contents of the loop is just to print i and go onto the next line. After the contents are done the ++i runs (adds 1 to i) and the condition is checked again. i is now 1 and i is still less than 3. Same story again but it prints 1 and turns i to 2; 2 is less than 3 so it runs again. When i is incremented again it now becomes 3, 3 is not less than 3 so the condition fails and it exits out of the loop; this is why 3 was never printed.
15th Aug 2016, 2:54 PM
+ 1
Thanks a lot :)
15th Aug 2016, 2:59 PM
Zafirah Mohamed iqbal
Zafirah Mohamed iqbal - avatar