The primitive type bool

New primitive type: bool.

bool is the smallest type. It stores either the value 0 or 1. We use bool for True or False statements. Here 0 stands for false, and 1 stands for true.

Boolean expressions:

/* For the following expressions, assume a and b are variables of the same type.
   For example, this all makes sense if a and b are both ints. If a is a float
   and b is a string then this will be problematic.
*/

a == b // Returns 1 if a is exactly equal to b. Returns 0 otherwise.

a != b // Returns 0 if a is exactly equal to b. Returns 0 otherwise.

a <= b // Returns 1 if a is less than or equal to b. Returns 0 otherwise.

a < b  // Returns 1 if a is less than b. Returns 0 otherwise.

a >= b // Returns 1 if a is greater than or equal to b. Returns 0 otherwise.

a > b  // Returns 1 if a is greater than b. Returns 0 otherwise.


// These next few expressions only make sense if a and b are of type bool.

!a     // Returns the opposite of a. So if a == 1, this returns 0.
       // If a == 0, then this returns 1.

a && b // Returns 1 if a and b are both 1. Returns 0 if either a or b is 0.

a || b // Returns 1 if at least one of a,b is 1. Returns 0 if both a,b are 0.

Example program:

#include <iostream>
using namespace std;

int main() {
     bool a = true; // This is the same as bool a = 1;
     bool b = false; // This is the same as bool b = 0;
     cout << "Here a is " << a << "\nand b is " << b << "\n.";
     cout << "The value a && b is " << (a&&b) << "\n";
     cout << "The value a || b is " << (a||b) << "\n";
     cout << "The value a == b is " << (a==b) << "\n";
     cout << "The value a != b is " << (a!=b) << "\n";
     cout << "The value !a is " << (!a) << "\n";
     cout << "The value (!a)==b is " << ((!a)==b) << "\n";
     cout << "The value !(b || (!a)) is " << (!(b || (!a))) << "\n";
}

Truth Tables

Suppose A,B,C are all variables of type bool. Write out a truth table for each of the following expressions.

1) A && B
2) (A || B) && C
3) A || (B && C)	// Note the difference between (2) and (3).
			// These parentheses are important.
4) C || (!A)
5) (!A) && B

Aside: DeMorgan's Laws

DeMorgan's Laws are rules that allow us to simplify some Boolean expressions. There are two of them. Here they are:

     !(A && B) is the same as (!A) || (!B).
     !(A || B) is the same as (!A) && (!B).

To prove these are the same, write out a truch table for each of the expressions:

6) !(A && B)
7) (!A) || (!B)
8) !(A || B)
9) (!A) && (!B)

We can also think of DeMorgan's Laws in terms of normal english sentences (This is a bit scary, because once you leave the world of math/logic it's a lot easier to have miscommunications.)

She's not at school or at home means the same thing as She's not at school and she's not at home.

UCLA school colors aren't blue and green means the same thing as Either blue isn't a school color or green isn't a school color.

If your boolean expressions are complicated you might have to apply DeMorgan's Laws more than once. For example

     ![(A || B) && C] = [!(A || B)] || (!C)
                      = [(!A) && (!B)] || (!C)

If Statements

If Statements are part of a larger topic called flow control. They allow us to direct our program to do different things based on the current situation.

Basic Syntax for If Statements

if( BOOLEAN_EXPRESSION_HERE ) {
    // This code runs if your boolean expression is true
}

If you want to run more than one line inside your if statement, you must use curly braces. If the inside of the statement only contains one line then braces are not necessary. In other words

if( BOOLEAN_EXPRESSION_HERE )
    // Just one line of code here

will work correctly.

Here's an example program:

#include <iostream>
#include <string>
using namespace std;

int main() {

     // First we ask the user for a string
     // and store it in the variable input.
     cout << "What kind of bear is best?" << "\n";
     string input;
     getline(cin, input);

     // If the input is "Black Bear", we output "Bears. Beats. Battlestar Galactica."
     if(input=="Black Bear") {
          cout << "Bears. Beets. Battlestar Galactica.";
          cout << "\n";
     }

     // If the input is anything else, we output "False. Black Bear."
     if(input != "Black Bear")
          cout << "False. Black Bear." << "\n";
     // Note: This if statement doesn't require curly braces

     return 0;
}

Extra options: else and else if

A standard if statement runs your code if the boolean expression is true, and does nothing if the expression is false. By adding "else" and "else if" statements, you can specify what the program should do if the original boolean expression was false.

if( EXPRESSION_1 )
        // This will run if EXPRESSION_1 is true
}
else if( EXPRESSION_2 ){
        // This will run if EXPRESSION_1 is false and EXPRESSION_2 is true
}
else if( EXPRESSION_3 ){
        // This will run if EXPRESSION_1 and 2 are false, and EXPRESSION_3 is true
}
// Can add more else if statements if necessary
else {
       // This will run if all previous EXPRESSIONs were false
}

// Note: Only one of these pieces of code will actually run. Once one expression is true, 
the remaining else/elseif statements are skipped.

Example Program

#include<iostream>
using namespace std;

int main() {
     double x = 0;
     cout << "Please input a decimal number: \n";
     cin >> x;

     if(x < 0)  // This says: if x is < 0 then print the thing.
          cout << "x is a negative number.\n";

     else if(x < 1) // This says: if the previous if failed, 
                         // AND x < 1, then print the thing.
          cout << "x >= 0 and x < 1.\n";

     else if(x < 2) // This says: if all the previous ifs failed, 
                         // AND x < 2, then print the thing.
          cout << "x >= 1 and x < 2.\n";

     else          // This says: if all the previous ifs failed, print the thing.
          cout << "x >= 2";

     // Note: This program will only ever output one sentence.
     // Once one of the if statements succeeds, the program will never look at
     // the rest of the statements.

     return 0;
}

Scopes of Variables

We've talked a little about the scope of a variable before, but with the introduction of if statments it gets more complicated. The scope of a variable is, roughly speaking, the places in your code where your variable is considered declared. For example:

#include <iostream>
using namespace std;

// the variable a has not been declared here

int main() {
    cout << "Please input an integer: \n";
    int a;     // now a has been declared, and we can use the variable
    cin >> a;
    return 0;
}

New Thing: When you declare a variable inside an if-statement, the scope of that variable is limited to the if-statement. In other words, if you declare a variable inside of an if-statement, it will be destroyed at the end of the if-statement. For example:

//Example with errors:

#include <iostream>
using namespace std;

int main() {
    int input;
    cin >> input;
    if (input < 3) {
        int i = 4000;
    }
    else {
        i = 2000;  // This line will give an error. i has not been declared in this scope  
    }
    cout << i;  // Similar to the above, i has not been declared in this scope.
                // Even though i is declared above, it is destroyed at the end of the if statment
}


//Fixed version

#include <iostream>
using namespace std;

int main() {
    int input;
    cin >> input;
    int i;
    if (input < 3) {
        i = 4000;  // i has already been declared, so we don't need the word "int"
    }
    else {
        i = 2000;
    }
    cout << i;  // Because i was declared in main(), it is available everywhere in main
}

Common Mistake: "a = b" versus "a == b"

Writing "a = b" is very different from writing "a == b". a = b will assign the value in b to the variable a, then return the new value. a == b tests if a and b are equal, but does not change the value of a or b.

Example Program

#include <iostream>
using namespace std;

int main() {
     bool a = 0;
     bool b = 1;
     if(a = b) {
          cout << "True!" << '\n';
     }
     else if(a != b) {
          cout << "False!" << '\n';
     }
     return 0;
}

// To do: Go through this program line-by-line and say what happens.

Practice Problem: Read some code

Here is a program:

#include <iostream>
using namespace std;


int main() {
     
     int a;
     cout << "Please input a starting number: ";
     cin >> a;

     if(a == 3)
          a = a+1;
     else if(a == 4)
          a = a-1;
     else
          a = a/2;

     cout << "After the first step we get a=" << a << "\n";

     if(a > 2 && a!= 4)
          a = 3;
     if(a == 3)
          a = a/2;
     else if(a == 0)
          a = a+2;
     else
          a = a+3;

     cout << "After the second step we get a=" << a << "\n";
     
     return 0;          
}

What does the program output for these different values of a?

To check your answers just run the code and see what happens.

Side note:

If you want your program to end early without going through every line, you can put in "return 0;" where you want it to stop. For example:

#include<iostream>
using namespace std;

int main() {
     int a;
     cin >> a;
     if(a==1)
          return 0;
     else if(a==2) {
          cout << "a was 2";
          return 0;
     }
     cout << "BLABABABABAB";
     return 0;
}

// If a==1, this program will output nothing
// If a==2, this program will output "a was 2" (and nothing else).
// If a is any other number, this program will output "BLABLABLABA" (and nothing else)

Practice Problems: Programming Exercises with If Statments

Problem 1:

Write a program that inputs 3 integers via cin and outputs the largest of them.

Ex: If the inputs are -9,204,2 then the output should be 204.

Problem 2:

Write a program that inputs 2 integers (I'll call them a, and b here), and outputs a number based on the sign of those integers.

Practice Problems: DeMorgan's Law

Use DeMorgan's laws to move the ! to the inside of each of the following expressions (you don't have to write out a truth table anymore... unless you want to?). People also call this simplifying the boolean expression.

1) ![ A && (!B)]
2) ![ (A && B) && C]
3) ![ !(A || B) && (!C) ]

Here are some more of the same questions, but we replace the letters A,B,C with some actual boolean expressions.

4) !( firstName == "Geoff" && lastName == "Iyer")
5) ![ x>0 || x == -1]
6) ![ (x+y == z && z != 0) || (y+z == x && x != 0) ]

For Fun Problem

Here's a longer problem involving using the wrong '=' sign in if statements. Read through it, guess what it will output, then run it to see if you are correct.


#include <iostream>
using namespace std;

int main() {
     bool a = 0;
     bool b = 1;
     
     if(a = b)
          cout << "Test 1: a = b evaluates to true\n";
     else
          cout << "Test 1: a = b evaluates to false\n";

     if(a = 0)
          cout << "Test 2: a = 0 evaluates to true\n";
     else
          cout << "Test 2: a = 0 evaluates to false\n";

     if(b = a)
          cout << "Test 3: b = a evaluates to true\n";
     else
          cout << "Test 3: b = a evaluates to false\n";

     if(b == a)
          cout << "Test 4: b == a evaluates to true\n";
     else
          cout << "Test 4: b == a evaluates to false\n";

     return 0;
}