We start with a program that loops until two odd numbers have been entered in a row. This program, by itself, has no practical purpose. It does, however, demonstrate the use of two booleans and the basic structure could be used for any task requiring the search for two consecutive values of types of values.
// A program that loops until two odd numbers in a row have been entered
// A demonstration of the use of booleans
// file: ch6xmpl2.cpp
#include <iostream.h>
void main()
{ bool oneOddFound = false; // to indicate if the previous number was odd
bool twoOddsFound = false;
int num;
while (!twoOddsFound)
{ cout << "Please enter an integer. The loop stops when ";
cout << "two odd numbers in a row are entered.\n";
cin >> num;
if ((num % 2) == 1) // There is a remainder so the number is odd
{ if (oneOddFound) // The previous number was odd
{ twoOddsFound = true;
}
else // the previous number was even so set oneOddFound to TUE
{ oneOddFound = true;
}
}
else // The present number is even
{ oneOddFound = false;
}
}
}
A second example that uses a boolean in a different way is in the first example of the switch statement
The next example of the use of the boolean uses arrays, a topic discussed in Chapter 7 of "The Story of C++". The idea is to search for a certain letter in an array of characters.
// A program to demonstrate the searching of an array and of the use of booleans
// file: ch6xmpl3.cpp
#include <iostream.h>
#include <ctype.h> // holds the declaration for 'tolower' - see below
const MAX_CHARS = 10; // an arbitrarily chosen number
void main()
{ char characters[MAX_CHARS] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
char toBeFound;
cout << "Please enter the character to look for\n";
cin >> toBeFound;
toBeFound = tolower(toBeFound); // change character entered to lower case
// since array only holds lower case
// tolower is a built-in function.
bool found = false;
int index = 0; // start from front of array;
while ((!found) && (index < MAX_CHARS)) // two ways a search can stop
// the value is found or
// all elements have been searched
{ if (toBeFound == characters[index])
{ found = true;
}
else
{ index++; // prepare to examine next element of the array
}
}
if (found) // the loop exited because the character was found
{ cout << "\nThe character is in the array";
}
else
{ cout << "\nThe character is NOT in the array";
}
}
Boolean variables in "The Story of C++"