How to choose a loop type for a situation? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

How to choose a loop type for a situation?

while, do while, for loop

20th Jan 2018, 12:44 PM
K.Suhanya
K.Suhanya - avatar
9 Answers
+ 2
Like @code learner said, if you know, or ask user, how many times you need to do something it's best to use for, like working with array. While is better when you need a certain condition to end the loop, like until user says "NO". In your example both are ok, but try checking them both and see which one takes you less time and is shorter. Also try running them in a program that shows you the compilation(?) time.
20th Jan 2018, 2:06 PM
rafal
+ 6
mm.....ya. that's correct
21st Jan 2018, 6:28 AM
K.Suhanya
K.Suhanya - avatar
+ 5
print 1-10 numbers. in this situation, how to choose.....??? because while & for loop, both can write the coding....
20th Jan 2018, 12:53 PM
K.Suhanya
K.Suhanya - avatar
+ 5
what is reason for choosing "for loop" ?
20th Jan 2018, 1:50 PM
K.Suhanya
K.Suhanya - avatar
+ 2
You can use for loop or while loop for printing 1 - 10 but my suggestion is for loop
20th Jan 2018, 1:44 PM
code learner
code learner - avatar
+ 1
when you know exact number of iterations directly or indirectly its for loop
20th Jan 2018, 12:48 PM
code learner
code learner - avatar
+ 1
else it is do while or while loop
20th Jan 2018, 12:48 PM
code learner
code learner - avatar
+ 1
because for loop is used when we know how many times to iterate (directly or indirectly) ,here you want to print 1-10 numbers that means you know , you need 10 iterations
20th Jan 2018, 1:54 PM
code learner
code learner - avatar
0
use your fav loop, thats all
20th Jan 2018, 8:40 PM
Koka Bart
Koka Bart - avatar