+ 11
Difference between for and while loop?
when to use for loop and when while loop?
7 Respuestas
+ 7
They are both nearly the same, just that in "for" loop, it is slightly more flexible. If you remember, for loop works this way :
for (initializationStatement; testExpression; updateStatement)
How it works is that, for loop does the initializationStatement, then testExpression. If testExpression is true, it will then process whatever is inside the loop and do the updateStatement, and going back into testExpressions until it becomes false. Once it becomes false, it will exit the 'for' loop and continue to process whatever is below that loop.
For 'while' loop, it only consist of this :
while (testExpression)
Basically, while loop will do this instead :
It will just start to text expression, if true, it will process whatever is inside the loop and come back to testExpression again until it becomes false. Once it becomes false, it will then exit the loop and continue processing the other datas below the loop.
The difference? After these two explaination, you will realize that while and for loop has 2 different things.
- 'for' loop has initializationStatement, 'while' does not have it.
- 'for' loop has updateStatement, 'while' does not has it.
This means that if you want to use 'while' loop, you have to make sure that you have a initializationStatement before the loop. You will also need an updateStatement inside the 'while' loop to prevent a infinite loop. for example :
int x = 6 //This is the initializationStatement
while (x<10)
{
x++; //This is the updateStatement
Console.WriteLine(x); //or cout if you are using C++
}
But as for 'for' loop, you don't need it since its already done, for example :
for (x=6;x<10;x++;)
{
Console.WriteLine(x); //Or cout if you are using C++
}
Another difference is that 'while' loop can become a 'do...while' loop, but they are similar to each other.
When to use those? If you are planning to create an integer that you are going to use for loops ONLY, I suggest in using 'for'. But honestly, its up to personal perfernce though.
+ 9
(for loop) have the beginig and the ending ,(for loop) keep going until the end condition ,but (while loop) have a condition and it's run if the condition is true
+ 9
I always used to get stuck in loops
so it might help me. ty.
+ 2
(while loop) do the command you write in first and then check if condition is true or false if it true redo it if false stop
(for loop) it is check the condition first if true do the command if false stop
i hope u understand
+ 2
for loop is used when we know the exact count and while is used when we don't know the count
+ 2
only syntax changed...otherwise same process