while
The while loop allows to repeat a statement as long as
a certain expression’s value is or converts to
true:
int i = 10;
while(i)
cout << i-- << endl;
i will be printed out as long as it is
greater than 0. Any valid expression can be the argument of a
while statement as long as it is or
can convert to a
bool.
The loop body can be missing and just like for any other
loop the control expression can be the result of a function:
printRandomNumbers()
{
int n = rand()%10;
cout << n << endl;
return n;
}
while(printRandomNumbers());
printRandomNumbers() prints out at each call a
random number between 0 and 9.
The
while statement will iterate until a 0
is generated.
Example
#include <iostream>
#include <ctime>
using namespace std;
printRandomNumbers()
{
int n = rand()%10;
cout << n << endl;
return n;
}
int main()
{
int i = 10;
while(i)
cout << i-- << endl;
cout << endl;
srand( (unsigned)time( NULL ) ); // Seed the random-number generation
while(printRandomNumbers()); // prints random numbers until 0 is generated
}
(Possible) Output
10
9
8
7
6
5
4
3
2
1
4
7
6
3
4
0