fbpx

C++: Loop Breaks

Bjarne-stroustrup
 


Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never generated as the first number in a loop, loop forever.

#include <iostream>
#include <ctime>
#include <cstdlib>
 
int main()
{
    srand(time(0));
    while(true)
    {
    	int a = 0 + rand() % 19;
    	std::cout << a << std::endl;
    	if (a == 10)
    		break;
    	int b = 0 + rand() % 19;
    	std::cout << b << std::endl;
    }
    return 0;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.