Difference between while loop and for loop.

Hi there !
Can u please tell me about the difference between while loop and for loop?

A while loop will generally loop until a condition is met.

A for loop will generally (but not always) run for a predetermined number of iterations.

http://www.cplusplus.com/doc/tutorial/control/
Last edited on
While loops generally go around an unknown number of times (until a condition is met), while a for loop usually has a known amount of times to loop around.

1
2
3
for (int i = 0; i < 3; i++) {
    //this goes around 3 times
}


1
2
3
4
5
6
int x = 0;
while (x < 5) {
    x++;
}

//this loop goes around 5 times, but it's not really known at the time it's created. 
The difference is in the syntax. Open a book on C/C++ and read about iteration statements.
They can both do the same things, but in general if you know how many times you will loop use a for, other wise use a while.

@LimeOats: Perhaps a better example?
1
2
3
4
5
6
7
8
9
10
bool again = true;
char ch;

while (again)
{
  cout << "Do you want to go again? ";
  cin.get(ch); cin.ignore(80, '\n');
  if (ch == 'n')
    again = false;
}
Last edited on
"for" is just a syntactic sugar for "while"
Topic archived. No new replies allowed.