+ 2

What is difference between while loop and for loop

when to use for loop and when to use while loop

16th Nov 2017, 6:05 PM
vignesh R M
vignesh R M - avatar
3 Answers
+ 5
FOR loops are great when you'll have some idea of how many iterations it'll loop through. WHILE loops are great for when you've no idea when the loop will end. EXAMPLES: for(int i = 0; i < 10; ++i) while(true) As you can see, the FOR loop has a clear path to its end point. While the WHILE loop is vague on when it'll actually end.
16th Nov 2017, 6:09 PM
AgentSmith
+ 2
@Immortal You're absolutely correct on that, and I apologize for being vague. When I said "are great for" I didn't mean to imply that it's limited to. Technically, they're the exact same thing, just set up differently to make certain tasks easier that you would have to type out differently otherwise. EXAMPLE: int i = 0; while(i < 10) { // code ++i; } SAME THING AS: for(int i = 0; i < 10; ++i) { // some code } ^As you can see by the examples, since we have better information on the exact amount of times we'll want to loop, the FOR loop greatly simplifies how we would do it with a while loop. Likewise, you can make a FOR loop infinite also, but it defeats the purpose of why the FOR loop was created. FOR was created to simplify how we were doing it prior. Loops are just loops at the end of the day, so you can use any of them as you see fit.
16th Nov 2017, 7:54 PM
AgentSmith