CMIS 102 logical operators Logical operators are very important. && is the logical AND operator. || is logical OR. ! is logical NOT. Warning: C++ also has & and | as operators but we won't be using them in this course, don't use them because it'll be an error in your program if you do. The result of and-ing two values is True only if both values are true, it's False otherwise (i.e. if either or both are False). The result of or-ing two values is True if either or both of the values are True, it's False only if both values are False. The "truth tables", completely defining these operators by showing the resulting value for all possible combinations of two truth values, are in the book. They are straight out of classical logic, which is based on human thought and language. In real-life and human language: if sunny OR weekend then go outside if sunny AND weekend then go outside if NOT rainy then go outside In logic and programming language: two truth values OR'ed together are True if either or both are True. Ex. booleanExpr1 OR booleanExpr2 Is True if booleanExpr1 is True or if booleanExpr2 is True (or if both are True). Is False only if both are False. two truth values AND'ed together are True only if both are True. Ex. booleanExpr1 AND booleanExpr2 Is True if booleanExpr1 is True and booleanExpr2 is True. Is False if either or both are False. a truth value NOT'ed reverses its truth value. Ex. NOT booleanExpr Is True if booleanExpr is False Is False if booleanExpr is True Here's some natural examples used as conditions for if statements: notice the spacing style char midExam; cin >> midExam; if (midExam=='A' || midExam=='B') cout << "congratulations!"; else if (midExam == 'C') cout << "could use some improvement"; else if (midExam == 'F') cout << "you're failing"; cin >> score; if (score<0 || score>100) cout << "Error. score must be between 0 and 100"; char ans; cin >> ans; if (ans=='y' || ans=='Y') //allows user to enter either case y/Y .... if (score>=90 && score<=100) //between 90 and 100 cout << "A"; cin >> ans; if (ans!='y' && ans!='Y') //anything but a y/Y cout << "whatever it is, it isn't a y or Y"; if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12) cout << "31 day month"; else if (month==4 || month==6 || month==9 || month==11) cout << "30 day month"; else cout << "February: 28 or 29 days"; The fact that the logical operators "short-circuit" isn't important to know now. Operator precedence is important. In an expression like ab+2||a b+2 || a (b+2)) || ((a b+2) || (a b+2 || a