Why use while instead of for | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 17

Why use while instead of for

in what situation we can use while loop instead of for loop I mean for loop is similar to while loop and simplified if compared to while so why use while instead of for

27th Mar 2017, 4:44 AM
Prudhvi Raaj
Prudhvi Raaj - avatar
3 Answers
+ 2
The [for] loop is an improved [while] loop basically. The second runs until the condition results false, the same what the first does with its condition (like "i < 10"), but it also can define a variable for the iteration only and modify its value each cycle by a given expression. You can leave both of the later mentioned part of the [for] loop to gain its base [while] loop either: int i = 0; for( ; i < 10; ) { i++; } You see, it's the same if I replace "for" with "while" only with the condition. The [for] loop is there to include the initialization and incrementation lines in the loop core too and make the code more clear. Without [for] we could write the same behaviour, but with it the code can be more easily overviewed and managed.
14th Apr 2017, 3:31 PM
Magyar Dávid
Magyar Dávid - avatar
+ 2
The for loop is uses when you want to loop through a more defined statement like an array. While the while loop is the contrary. Go to your solo learn javascript tutorials and compare and contrast how the two loops where used in their different instances
27th Mar 2017, 5:22 AM
Fido 🇳🇬
Fido 🇳🇬 - avatar
+ 1
Mostly, for loop is used for iterations, whereas while loop is used to evaluate or do stuff while the given statement is true.
26th Apr 2017, 2:31 AM
ram kumar
ram kumar - avatar