+ 2

What is the difference between for loop and while loop?

Answer me

28th Nov 2017, 1:14 PM
Coding Niffler
Coding Niffler - avatar
3 Answers
+ 3
When you have a concept of an end, a general idea of how many iterations, it's better to use a FOR loop because of how it sets up its conditions. Whereas a WHILE loop is good for other conditions where you may not realize a certain amount of iterations taking place. It's worth noting that they're both technically the same thing; a loop. The FOR loop was created to make how we were doing it easier. :::: WHILE LOOP :::::: int maxIterations = 5; int i = 0; while(i < maxIterations) { // some code ++i; } ^That's how a WHILE loop is used to do what we want a FOR loop to do. As you can see, there is a lot more to it and some things can be easily forgotten. :::: FOR LOOP :::::: for(int i = 0; i < maxIterations; i++) { // some code } ^As you can see, that makes what we originally did a lot easier and mostly on the same line. Same exact thing, except FOR makes it easier to do. Again, they're all loops, so they're essentially the exact same thing. The FOR has its conditions and a set amount of iterations (until i gets to maxIterations). Whereas with the WHILE loop, you could have it going forever until you break the loop or something else is met; no real determination of a max amount of iterations. while(true) { // some code } ^Loop infinitely until the loop is broken.
28th Nov 2017, 1:28 PM
AgentSmith
+ 2
thanks friends
28th Nov 2017, 3:59 PM
Coding Niffler
Coding Niffler - avatar
+ 1
you can usually use any of those as you prefer, the difference is small : the for loop allows to specify how to increment the loop counter (less easy to forget!) . the while loop is more appropriate when waiting for the condition to change with no knowledge of the number of iterations.
28th Nov 2017, 1:32 PM
ifl
ifl - avatar