For and While loops differ in anyways? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

For and While loops differ in anyways?

24th Dec 2016, 10:43 PM
Umair Ahmadh
Umair Ahmadh - avatar
6 Answers
+ 8
As a general rule of thumb: Use a for loop if you know how many iterations are to be completed, such as iterating through a vector. Use a while loop in the opposite way; when you can't be sure how many iterations will be completed, which is why we use while for game loops and not for, haha.
25th Dec 2016, 3:26 AM
Cohen Creber
Cohen Creber - avatar
+ 3
"for" is the easiest way to implement a loop condition based on a count variable (you can declare and test the condition in the same command), "while" is used when the loop is based on another type of condition.
24th Dec 2016, 11:00 PM
Michael Isac Girardi
Michael Isac Girardi - avatar
+ 2
they both have basically the same function. but for loop is more frequently probably for convenience sake ...
24th Dec 2016, 10:47 PM
Cody Arthur
Cody Arthur - avatar
+ 2
1- for has its condition , ckeck & end of in/decrement in the same line =>Which is good for understanding and making the code shorter 2-for is only used in case of you know the number of iterations . nice to meet you .
30th Dec 2016, 6:25 AM
Mohamad Alkhawarizmi
Mohamad Alkhawarizmi - avatar
+ 1
both of them functions in a same way but in for loop instilization condition Inc/Dec is done in a same line which makes our program short and it will be much easier to understand
25th Dec 2016, 2:16 PM
sreya
sreya - avatar
0
there are instances where one might be more convenient to use, as @Cohen Creber has pointed out. however, you can use for loops even when you do not know how many iterations; and while loop when you know how many iterations.
12th Feb 2017, 8:36 AM
Nathan Algren