Back to DFS's C Page


Boolean (Logical) Operators

The Man

George Boole (1815-64) was a self-taught English mathematician who developed an "algebra of logic" which is now called Boolean algebra or Boolean logic.

His Operators

The operators can be used to evaluate the truth value of one or more conditional (or test) statements.There are three operators which we will be concerned with:

&& AND requires that both (all) conditions be TRUE
|| OR requires that at least one of the conditions be TRUE
! NOT reverses the truth value - TRUE to FALSE and vice versa

These operators can be used singly or in combination. To understand how they function, it is probably easiest to use logic gates or truth tables, substituting TRUE for 1 and FALSE for 0, as shown below.

The Code

The following code segments illustrate how Boolean conditions and operators can be used to exit from loops and/or programs. The first two code segments perform exactly the same task. The first uses the OR operator while the second uses a combination of NOT and AND. The third shows how to allow the user to exit a program gracefully using the built-in function exit(). Note the use of parens to enclose conditionals when multiples are used.

/* Get a value; accept only a natural number between one and ten, inclusive */
do
{
   printf("Type a natural number less than or equal to 10 and hit RETURN: ");
   scanf("%i", &num);
   if (num < 1) 
      printf("Your number is too small!\n");
   if (num > 10)
      printf("Your number is too big!\n");
}
while ( (num < 1) || (num > 10) );

/* Get a value; accept only a natural number between one and ten, inclusive */ do { printf("Type a natural number less than or equal to 10 and hit RETURN: "); scanf("%i", &num); if (num < 1) printf("Your number is too small!\n"); if (num > 10) printf("Your number is too big!\n"); } while (! ( (num >= 1) && (num <= 10) ) ); /* Check to see if the user wants to exit the program * This code segment is usable within a larger main-line loop */ do { /* Main program code would go here */ printf("Do you want to exit the program? (Y/N) "); scanf("%c", &yn); if ( (yn == "Y") || (yn == "y") ) exit(0); } while ( !( (yn == "Y") || (yn == "y") ) );


© DFStermole: 21 Aug 97
HTMLified: 3 Oct 98