Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more: (untagged)
I am having difficulty understanding the difference between a For Loop and a While Loop. When do I use one over the other. They appear to be so similar. Is there a simple explanation for a beginner to grasp?
Posted
Comments
Maciej Los 17-Mar-15 17:12pm    
What language?
Sergey Alexandrovich Kryukov 18-Mar-15 0:24am    
The whole concept of "difference" is wrong. There is no a way to correctly define what to call "difference". Learn how one form of loop works and how another form works.
—SA

1 solution

A while-loop loops as long as it's predicate (the expression in the braces following the while-keyword) is true:
C#
bool keepRunning = true;
while(keepRunning)
{
   // do something

   if(! UserWantsToKeepRunning()) // imagine some user input
      keepRunning = false;
}

A for-loop usually (as a beginner you shouldn't care about non-standard uses yet) increments or decrements a variable with a given starting-value on each loop until the variable reaches a value so that the predicate of the for-loop is no longer true:
C#
// starts with x = 0
// increments x each loop by 1
// when x = 10, x < 10 becomes false, loop ends
for(int x = 0; x < 10; x++)
{
}

You usually use a for-loop if you need a variable running from a start value to an end value and a while-loop if you don't know when writing the code how many loop-runs will be required when your program is executing.

It's easy to "emulate" a for-loop with a while-loop (just an academic example, no real use):
C#
int x = 0;
while(x < 10) // will evaluate to false as soon as x == 10
{
   x++;
}
// when reaching this point, x == 10
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900