For vs. While | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

For vs. While

What are the main differences between the two loops? I learned that ages ago but I forgot.

24th Aug 2020, 7:20 AM
Phil
10 Answers
+ 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
24th Aug 2020, 7:26 AM
🈂️Toma
🈂️Toma - avatar
+ 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.
26th Aug 2020, 5:13 AM
Sonic
Sonic - avatar
+ 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.
24th Aug 2020, 7:27 AM
Ćheyat
Ćheyat - avatar
+ 2
Ćheyat Don't worry, happy to help, I often do typos too :) I will delete the response...
24th Aug 2020, 7:35 AM
🈂️Toma
🈂️Toma - avatar
+ 2
Phil glad to help.
24th Aug 2020, 7:44 AM
🈂️Toma
🈂️Toma - avatar
+ 1
🈂️Toma Sorry , Typo! Thanks for mentioning!
24th Aug 2020, 7:34 AM
Ćheyat
Ćheyat - avatar
+ 1
thanks guys!
24th Aug 2020, 7:43 AM
Phil
0
Who decrease my explanation?! May be i don't know english well for explanation, but the idea is correct.
26th Aug 2020, 5:26 AM
george
george - avatar
- 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++.
24th Aug 2020, 11:11 AM
george
george - avatar
- 3
btw, they both can do the same thing; however, ‘for’ is more readable in nested loops.
24th Aug 2020, 8:21 AM
Flash