Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 9
Hello, Abdulkareem Fallaha ! for(literally "for") - applies when you need to do something in a certain range. that is, in human language it will sound like something like: "for this range we are doing something." while(literally "while") - is used when you need to do something undefined number of times before the fulfillment of a specific condition. that is, in human language it will sound roughly like: "doing something until the condition is fulfilled."
14th Jul 2018, 5:36 AM
Alexander Sokolov
Alexander Sokolov - avatar
+ 5
there ain't any hard and fast rule, they are interconvertable to each other in most of the cases. Usually when i require an infinite loop , then i prefer while. basically use while loop when you don't know how many times you want to iterate (you just want to satisfies a particular condition), in the scenario while is preferable to use, and when u know how many repeation you want then use any of your choice, i prefer for in the scenario.
14th Jul 2018, 5:42 AM
Nikhil Dhama
Nikhil Dhama - avatar
+ 3
You can use for if you have a set amount of a loop you want to do. While can be used until the loop is completed.
15th Jul 2018, 5:01 AM
Apple Blossom
Apple Blossom - avatar
+ 3
Apple Blossom While also has the capability to be set to the number of loops you want to perform, though conceptually you are right: for is more obviously suited to the task. In practice most programmers tend towards one or the other as a rule (usually for these days, particularly given that alternative for in variant popular particularly in web programming) and only fall back to the other when there is a problem of some kind. Under the hood there are some subtle alternative behaviours but these may be more suitable to discover by experience.
15th Jul 2018, 9:14 AM
Peter David Carter
Peter David Carter - avatar
+ 2
It doesn't really matter which one you use. They are entirely interchangeable. Use what's convenient. For loops are convenient if you haven't already got a variable to count the iterations. While loops are convenient if you already have a variable to count the iterations, and if you want to keep using that variable outside of the loop.
14th Jul 2018, 6:17 AM
James
James - avatar
+ 2
For is used when you need to do a loop a predetermined number of times. While is used when you need that something occurs until a condition is done. I hope it will be good enough for you!
14th Jul 2018, 9:45 AM
Jose Esteve
Jose Esteve - avatar