+ 2

How for loop work ? I am really confused with it.

4th Mar 2017, 12:06 AM
Sani Suryavanshi
Sani Suryavanshi - avatar
2 Answers
+ 14
For loop should be used when you know how many times you want to repeat some code. There's a simple example: for (i=0; i<5; i++) { some code } 1. i=0 --> you start with index 0 2. i<5 --> check if your index is less than 5 (0<5 is true so you continue) 3. do some code inside loop 4. i++ --> add 1 to your i index, so it's 0+1=1 5. i=1 --> index is 1 6. check if index is less than 5 (1<5 so you continue) 7. .... etc Loop ends when your condition (i<5) isn't true. So when i=5, 5<5 is false and you quit loop.
4th Mar 2017, 12:33 AM
Wiola
Wiola - avatar
+ 2
for(int i=0; i<10; i++){ Do something here 10 times } basically is says a variable named i equals 0. you want to run the loop until the variable i is no longer less than 10. each time it runs you want to add 1 to the variable I.
4th Mar 2017, 12:36 AM
LordHill
LordHill - avatar