previous | index

Controlling Loops with Boolean Flags

Our previous recursive increasingOnIntegerRange could also be written with a while statement:

bool increasingOnIntegerRange(int f(int), 
                              int low, 
                              int high) {
    if ( low == high )
        return true;
    if ( f(low) < f(low+1) )
        return increasingOnIntegerRange(f, 
                                        low+1, 
                                        high);
    return false;
}
bool increasingOnIntegerRange(int f(int), 
                              int low, 
                              int high) {
    bool increasing = true;
    while ( low < high && increasing ) {
        increasing = f(low) < f(low+1);
        low++;
    }
    return increasing;
}

Note the use of the increasing variable as a "flag" controlling the loop.

Note also that && is the conjunction (and) operator in C++.

expression1 && expression2 is the same as (and expression1 expression2) in Racket.

Here is a Wiki Reference (in a separate window) on C++ operators and their precedence.


previous | index