+ 1

What's the difference between a while and a for loop ?

Hey guys, I wonder when we should pick a while loop or when wd should pick a for one, thanks for your answers :)

14th Oct 2017, 10:27 PM
Nicolas Nanou
3 Answers
+ 19
Tamra's explanation is awesome đŸŒč💝. As an example compare these three guys together. int foolish(int n) { return --n; } //... inside main() ....// //... while loop int x = -1; bool isExit = false; while (!isExit) { cout << "What's your number?! "; cin >> x; if (foolish(x) == -1) isExit = true; } //... do...while loop char ch = 'n'; isExit = false; do { cout << "Exit from game?(y)es / (n)o"; cin >> ch; switch (ch) { case 'y': case 'Y': isExit = true; break; case 'n': case 'N': cout << "Playing ..."; // calling play function break; default: cout << " invalid input!"; } } while (!isExit); //... for loop and do while int arr[100]; int n = 0; do { cout << "How many numbers?(less than 100)"; cin >> n; } while (n >= 100); for (int i = 0; i < n; ++i) { cout << "num " << i + 1<< ": "; cin >> arr[i]; }
16th Oct 2017, 8:22 AM
Babak
Babak - avatar
+ 15
while is better when you don't know how many times the loop will execute. All it checks for every loop is a condition. Ex: Waiting for a user to input a certain number or command. for is better for working with arrays, or to use a certain set or pattern of numbers. It has a counter and incrementer built in, so it's easier to manage.
14th Oct 2017, 11:00 PM
Tamra
Tamra - avatar
+ 1
Thanks foe your help I think I understood 😊
14th Oct 2017, 11:02 PM
Nicolas Nanou