+ 3
What is the difference between for loop and while loop
8 Respostas
+ 6
they perform the same thing,only difference is their syntax:
for(var i=0;i<5;i++);
while(i<5);
the for loop gives you the ability to declare the variable and specify its value of incrementation in its parameter
+ 6
A for loop is used to iterate through something and a while loop can be used for iterating and doing something while something is true
+ 4
in addition of Brains post I should say for loop is used when u want to perform something for some number of times.
while ,is for cases that u want do something until some condition is true or false...
+ 4
a while loop is very simple: as long as the condition is true, the code inside the loop will run. for example:
while (A) {
...
}
will run as long as A is true, and will break if A is false or if a break; is added somewhere in the loop.
with for loops... it depends on the language. in languages like C, C++, C#, Java and JS, a for loop is different to a for loop in Python or Ruby, for example.
in C, C++, C#, Java and JS, a for loop is declared the following way:
for (declaration; condition; what happens after every iteration of the loop)
the declaration part can be done before the loop, and what happens after each iteration. for example,
for (int i = 0; i < 10; i++) {
...
}
is equivalent to:
int i = 0;
for (; i < 10;) {
...
i++;
}
however, the second example is the exact same as a while loop:
while (i < 10) {
...
i++
}
so... the for loop is just a "cleaner" version of the while loop, in terms of syntax.
for languages like Python, the for loop is a little different. it behaves the same way as the foreach loop in C#. it allows you to iterate through some collection, as shown below:
for n in [0,1,2,3]:
...
for every iteration of the loop, n will be the next element in [0,1,2,3].
for n in [0,1,2,3]:
print(n)
this will print all the elements in [0,1,2,3]; every iteration will print the next element.
this means that it can be used for things like strings. for example:
for n in "Hello, World!":
...
in the first iteration, n = 'H'; in the second iteration, n = 'e'; in the third, n = 'l'; and so forth.
apologies for the lengthy explanation... I probably made it sound a lot more complicated than it really is. anyways, I hope this helps. đ
+ 4
đevil octopus Nice explanation!đđ
+ 1
while loop can run only if the condition specified is true,else it gets terminated,but for loop has no such constraints
+ 1
for loop is used to execute something for specific number of times where as while loop is used to execute the target statement as long as the given condition is true
0
it's very easy .when we already know the loop increment number then and then use for loop.