0
For vs. While
What are the main differences between the two loops? I learned that ages ago but I forgot.
10 Antworten
+ 4
The for loops runs a certain operation for a known number of times like: print "hello" for 10 times.
A while loop runs a certain operation while the condition is true, not needing to know the amount of times to run the loop.
Also please refer to this articles and avoid asking questions that have been ask before:
https://www.sololearn.com/discuss/1522646/?ref=app
https://www.sololearn.com/discuss/2039034/?ref=app
https://www.sololearn.com/discuss/400480/?ref=app
https://www.sololearn.com/discuss/56119/?ref=app
https://www.sololearn.com/discuss/217004/?ref=app
https://www.sololearn.com/discuss/52079/?ref=app
+ 4
For is usually to iterate a loop a fixed number of times whereas while is used to iterate while a specific condition is satisfied.
+ 2
In 'for' loop the initialization once done is never repeated. In while loop if initialization is done during condition checking, then initialization is done each time the loop iterate. In 'for' loop iteration statement is written at top, hence, executes only after all statements in loop are executed.
More info: https://techdifferences.com/differenece-between-for-and-while-loop.html#:~:text=In%20'for'%20loop%20the%20initialization,each%20time%20the%20loop%20iterate.&text=In%20'for'%20loop%20iteration%20statement,statements%20in%20loop%20are%20executed.
TL;DR: Just use 'while' loop for when there is no 'counter' needed.
+ 2
Ćheyat Don't worry, happy to help, I often do typos too :) I will delete the response...
+ 2
Phil glad to help.
+ 1
🈂️Toma Sorry , Typo! Thanks for mentioning!
+ 1
thanks guys!
0
Who decrease my explanation?! May be i don't know english well for explanation, but the idea is correct.
- 1
Both are for looping, if you know number of iterations you need use for, otherwice use while with break condition. It is the base using of loops.
do{}while(false) used if you have at least 1 iteration. also can be used if you have a lot of if else if else if else statements. In this case you can use if statement and break.it is very useful in c++.
- 3
btw, they both can do the same thing; however, ‘for’ is more readable in nested loops.