O'Reilly logo

C++ Data Structures and Algorithms by Wisnu Anggoro

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Loop statement

There are several loop statements in C++, and they are forwhile, and do...while. The for loop is usually used when we know how many iterations we want, whereas while and do...while will iterate until the desired condition is met.

Suppose we are going to generate ten random numbers between 0 to 100; the for loop is the best solution for it since we know how many numbers we need to generate. For this purpose, we can create the following code:

// For.cbp#include <iostream>#include <cstdlib>#include <ctime>using namespace std;int GenerateRandomNumber(int min, int max){    // static used for efficiency,    // so we only calculate this value once    static const double fraction =        1.0 / (static_cast<double>(RAND_MAX) + 1.0); // evenly distribute ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required