+ 5

What is the difference between the for loop and the while loop?

31st May 2018, 3:26 PM
Sonia Singh
Sonia Singh - avatar
2 Réponses
+ 4
'for loop' is a means of simplifying how we use to do the same concept with a 'while loop.' When you have some idea of how many iterations will happen, the 'for loop' is ideal. When you don't, the 'while loop' is ideal. EXAMPLES: FOR LOOP as a WHILE LOOP: int i = 0; while( i < 10) { DoSomethingHere(); ++i; } ^That's how we use to do FOR loops. Here is the FOR loop equiv of that type of loop. for(int i = 0; i < 10; ++i){ DoSomethingHere(); } As you can see, we simplified how we were previously doing it and that's the purpose of the FOR loop. WHILE loops are great for conditions that you don't necessarily know when will end or how many iterations will happen. WHILE LOOP: while(true) { if (thisHappens) { break; } DoSomethingHere(); } Anyways, this is just a basic means of summing it up. With that example, you should be able to see what's going on with them and what they do. Use them in whatever way you can think up, as there are many ways of utilizing them for various purposes. As you can also see, you can accomplish the same thing in either.
31st May 2018, 3:39 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 3
they both loop based on a condition. I'm pretty sure the while loop checks the condition first and in a for loop you can increment right in the condition, whereas a while loop can easily be an infinite loop if you forget to increment within it or create some sort of break point. sorry if that was a bad explanation.
31st May 2018, 3:41 PM
Brent
Brent - avatar