While Loops can be used like For Loops, however, they have some differences.
Here’s the syntax:
while (condition){ // code }
or
do{ } while(condition);
To be truthful, I’ve never used the second example.
While Loops can be used in a similar way to For Loops; as an example, while x < 10, do some thing, then add one to x each loop.
However, the difference is that you don’t have to use it for iterating.
How about this: you have 10 cups, and there’s a marble under one of them, the computer has to find the marble. A For Loop would look under all 10 cups before finishing, whereas, a while loop would stop the loop when it found the marble. This doesn’t make much difference with such small number, but imagine the difference over a thousand cups.
This example below is a program that generates a random number between 0-100. The user than has to guess the number, as program tells the user higher or lower. It’s called a Bracketing Search.
#include <iostream> using namespace std; int main() { int guess = 0; // users guess. int t = 0; // number of tries. srand(time(0)); // creates a seed based on the ever changing time. int r = 1+ rand() % 100; // generates a rand # between 1-100. // while guess is not the random number //and number of tries is less than 10. while (guess != r && t < 10) { cout << "Guess a number between 1 and 100." << endl; cin >> guess; if (guess > 0 && guess < 100) { if (guess == r) { cout << "You win! You guessed " << r << "!!!" << endl; } else if (r > guess) { cout << "HIGHER" << endl; } else { cout << "LOWER" << endl; } t ++; } else { cout << "Invalid Input" << endl; } } cout << "Number of tries: " << t << endl << endl; if (t == 10) { cout << "Sorry no more chances!" << endl; } }