Boolean Expressions and Selection


Introducing control to programs

Boolean expressions to describe conditions

The Boolean data type

Relational operators

How Booleans get used: if statements

Logical operators

Boolean functions

Short-circuiting logical expressions

Examples: evaluating Boolean expressions

Suppose we have the following variable declarations
int iDataX = 13;
int iDataY = 7;
int iDataZ = -3;
char cData = 'd';
Evaluate the following expressions as true or false: Which of those expressions `short-circuits'?

Examples: programming with Booleans and if

Here's a program that will tell a user if they entered a positive or a negative number:
#include <cstdio>

int main()
{
   int iUserInput;

   printf( "Please enter an integer\n");
   scanf("%d", &iUserInput);

   if (iUserInput < 0) 
   {
       printf( "You entered a negative number\n");
   }
   
   if (iUserInput > 0)
   {
       printf( "You entered a positive number\n");
   }

   if (iUserInput == 0)
   {
       printf( "You entered 0\n");
   }
}


If, else statements

If statements

Single-statement If-else's

Extended if-else statements

Nested If-else statements

Common use: error checking

One of the most common uses for if statements is error checking:

Common use: different control streams

Another common use of if statements is when there are completely different actions to be taken based on user input:
void get_command()
{
  bool bQuit = false;
  char cCmd;

  // prompt user and get command
  printf( "Enter S to calculate square roots\n");
  printf( "      X to translate hexadecimal values\n");
  printf( "   or Q to quit\n");
  scanf("%c", &cCmd);

  // handle the current command
  if (cCmd == 'S') {
     square_root_routine();
  } else if (cCmd == 'X') {
     translate_routine();
  } else if (cCmd == 'Q') {
     bQuit = true;
  } else {
     printf( "Invalid command\n"); 
  }
  
  // if user hasn't asked to quit,
  // go through whole cycle again
  if (!quit) {
     get_command();
  }
}

Switch statements

int switch example

Switch types, default and break statements

char switch example

As pointed out, switch also works with characters:

bool bQuit = false;
char cCmd;

printf( "Please enter your next command\n");     
printf( "    A to add new entry\n");     
printf( "    L to look up an entry\n");     
printf( "    Q to quit\n");     
scanf("%c", &cCmd);

switch (cCmd)
{
   case 'a':
   case 'A':  add_entry();
              break;
   case 'l':
   case 'L':  lookup_entry();
              break;
   case 'q':
   case 'Q':  bQuit = true;
              break;
   default:   printf( "Invalid command entered");
}
Note how we left out the break statements to allow upper and lower case commands to be treated the same