Borthamonth Borthamonth - 1 year ago 78
C++ Question

"and" and "or" operators

I'm new to coding and currently following the jumping into c++ book. I was making a slot machine that loops until all three strings have the same value. I'm confused as to why in this code the "or" operator is giving the desired result rather than the "and" operator. I wanted the program to check for both and that both need to be true, but that only works if I use the "or" operator. Thanks :)

using namespace std;

int randomNum(int low, int high) {
return rand() % (high - low) + low;

int main()
string slot[3] = { "Apple", "Banana", "Pumpkin" };
string slotA;
string slotB;
string slotC;
int guess = 0;

do {
slotA = slot[randomNum(0, 3)];
slotB = slot[randomNum(0, 3)];
slotC = slot[randomNum(0, 3)];
cout << slotA << "\t" << slotB << "\t" << slotC << "\n";
} while (slotB != slotC || slotB != slotA);

cout << "You won the jackpot in " << guess << " guesses!";

return 0;

Answer Source

Your stop condition should be:

while (!(slotB == slotC && slotB == slotA));

However, in Bool-Algebra !(slotB == slotC && slotB == slotA) is equal to slotB != slotC || slotB != slotA

This rule is called De Morgan Law

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download