Logical operators && ||

&&  	logical AND	
	left_expr && right_expr  
       is True (1) only if both left and right are True
       is False (0) if either or both are False

||  	logical OR
	left_expr || right_expr  
        is True (1) if either or both left or right is True 
	it's False (0) only if both are False


cin >> num;
if (num<1 || num>10)  //true if num is < 1 or if num > 10
  cout << "Error.  Must be between 1 and 10";

----------------------------------------

cin >> num;
if (num>=1 && num<=10)  //true if num is >= 1 and is <= 10  
  cout << "Valid input.  Is between 1 and 10";

Logical operators have lower precedence than the relational operators. In the above expressions the relational sub-expressions are evaluated first.


//error-checking loop until get valid input
cin >> num;
while (num<1 || num>10) {
  cout << "Error.  Must be 1 thru 10 only. Re-enter: ";
  cin >> num;
}
// now num between 1 and 10 , inclusive

Mistakes:
syntax error:
num<1 || >10       // can't have 2 consecutive operators

useless conditions:
num<1 && num>10    //is always False, num can't be both <1 and >10
num>1 || num<10	   //is always True, whatever num is.  
num==2 || 3        //is always True, not testing if num is 2 or
           3.  Truth value of num==2 ORed with 3 (non-zero (true)).

-------------------------------------------------

Examples:

//input a grade, test if it's a letter grade ABCDF
char grade;
cin >> grade;
if (grade=='A' || grade=='B' || grade=='C' || grade=='D' ||grade=='F')
  cout << "Valid grade";
else
  cout << "Invalid grade: " << grade << endl;

-------------------------------------------------

//input a valid grade.  Error-checking loop
cin >> grade;
//while not A and not B and not C and not D and not F...
while (grade!='A' && grade!='B' && grade!='C' && grade!='D' && 
       grade!='F') {
  cout << "Invalid grade: " << grade << "  Reenter: ";
  cin >> grade;
}
//after the loop know that grade is valid.  
//rest of code doesn't have to worry about it being invalid

--------------------------------------------------

//counts of lowercase letters, uppercase letters, others
//without using islower, isupper functions
if (c>='a' && c<='z')       //lower letters are continuous in ASCII
  lowers++;
else if (c>='A' && c<='Z')  //upper letters continuous in ASCII
  uppers++;
else
  others++;

-------------------------
&& has higher precedence than ||
//counts of letters and all other chars

if (c>='a' && c<='z' || c>='A' && c<='Z')
  letters++;
else
  others++;

//Evaluation order: the 4 relational ops first, then the 2 &&'s, 
//then the ||


//extra parens for readability, but they don't change meaning:
if ((c>='a' && c<='z') || (c>='A' && c<='Z'))

//too many parens for readability, but they don't change meaning:
if (((c>='a') && (c<='z')) || ((c>='A') && (c<='Z')))


A program that uses everything so far: gpa.cpp

Next (switch)


©David Wills