+ 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 :)
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];
}
+ 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.
+ 1
Thanks foe your help I think I understood đ