For loop vs while loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

For loop vs while loop

I am little bit confused when to use which loop. please explain me with details. example will be appreciated.

19th May 2017, 12:03 PM
Magic105
7 Answers
+ 4
For loops: Decide how many times to loop, You can iterate backwards or forwards, (Optional)You can do an infinite loop, You can declare an integer inside for loops While loops: Decide how many times to loop, You can do an infinite loop, (Optional)Use an existing integer to loop
19th May 2017, 12:11 PM
Complex
Complex - avatar
+ 5
@C0MPL3X Infinite loop... How about this? for(;;) print("Itaiyo!") //I try to make it look like rust
19th May 2017, 12:33 PM
Yanothai Chaitawat
Yanothai Chaitawat - avatar
+ 4
You make me laughing 😂
19th May 2017, 12:41 PM
Yanothai Chaitawat
Yanothai Chaitawat - avatar
+ 3
I always do B) xD
19th May 2017, 12:45 PM
Complex
Complex - avatar
+ 3
You can achieve the same with all types of loops, but some are more elegant than other's in my opinion
19th May 2017, 1:01 PM
‎ɐısıօլɐ
‎ɐısıօլɐ - avatar
+ 2
Yeah look at the For loops: (Optional) You can do an infinite loop :P
19th May 2017, 12:39 PM
Complex
Complex - avatar
+ 2
Typically you will use a for loop when have a preset number that you want it to run, such as the looping through every element in a list/array until the array length is reached. A while loop is commonly used when you don't have a set number to loop through, but you know the condition that it will run under, such as continue to run a game until the user choice is to quit then exit or continue to except student grades until the teacher enters the value q. I hope that helps
20th May 2017, 12:09 AM
Timothy Doolittle
Timothy Doolittle - avatar