Tuesday, April 10, 2012

User Input

One of my favorite things to include when writing personal programs is user input. I've used this to make trivia, mad libs, and ASCII art programs. It's pretty straightforward in Python and C++ and a little more complicated in Java. Let's say I want a program that greets a user by name, and maybe some other information like age or location.


name = raw_input("What is your name?")
location = raw_input("Where do you live?")
print "Hello, " + name + " from " + location


int main ()
{
    cout << "What is your name? ";
    cin >> name;
    cout << "Where do you live? ";
    cin << location;
    cout << "Hello, " << name << " from " << location << endl;
}


import java.util.Scanner;

public class UserInputExample {

     public static void main (String[] args) {

        Scanner userInput = new Scanner(System.in);
        System.out.print("What is your name? ");
        name = userInput.next();
        System.out.print("Where do you live? ");
        location = userInput.next();
        System.out.println("Hello, " + name + " from " + location);
    }
}
  • In Python, the optional prompt that is passed to raw_input will be printed on the screen. 
    • This function will wait until it encounters a newline character, and then it will convert whatever was typed by the user into a string.
  • In C++, the cin keyword acts like Python's raw_input, in that it converts whatever is typed into a string.
    • However, cin waits for any whitespace, rather than just a newline character.
    • To avoid this complication, getline can be used.

      cout << "What is your name?"
      getline (cin, name);
    • getline takes whatever is typed until it encounters a newline character, and sets it to the provided variable name.
    • Also, unlike Python, the prompt is not part of cin, so you must include anything you want to ask the user for above the cin line.
  • In Java, we have to import a built in Java class, Scanner, that handles input. 
    • When this class is instantiated, you have to specify that you want user input, by passing System.in to the constructor.
    • Like C++, the prompt and user input are separate.
    • In order to get the input you use Scanner's next() method, which returns input that ends with a delimiter. 
      • The next() method is set to use any whitespace as its default delimiter (meaning it will return the input once it encounters any whitespace), but this can be customized by passing your desired delimiter to the method: userInput.next("\n")

Friday, January 20, 2012

Classes: Inheritance

One of the biggest aims of object-oriented programming is code reuse. Why write and debug your own code, when there's already code that does the same thing? Inheritance is a form of code reuse that is especially handy for specializing a class that already exists. When a superclass is inherited by a subclass all of its attributes and methods are passed down. You can then specialize by adding your own unique attributes and methods.

For instance, let's say you're writing a laptop class. There's already a computer class that includes a word processor, access to the internet, a terminal, a keyboard, and a mouse. Laptops use (or can use) all of these things, so you don't need to rewrite all of that code. Instead, you can use inheritance to implement all of this code, and add some of your own (smaller, a track pad instead of a mouse, etc). You could also write a desktop class that also inherits code from the computer class.

Python


class Laptop (Computer):
    """ A laptop computer"""
    def __init__ (self, monitor_size)
        self.size = monitor_size


C++


class Laptop: public Computer
{
    private:
        int size;

    public:
        Laptop (int monitor_size)
        {
            size = monitor_size;
        }
};


Java


public class Laptop extends Computer {

    private int size;

    public Laptop (int monitorSize) {
        size = monitorSize;
    }

}

  • In Python, creating a subclass is the same as creating a superclass, except the keyword "object" that is normally in the parenthesis is replaced by the name of the class you are inheriting from ("Computer" in this case).
  • In C++ a subclass is defined with the following structure:

    class SubClassName: accessSpecifier SuperClassName
    {
        code;
    };
    • The access specifier controls the class's visibility, and this can be public, private, or protected. Public allows the class to be accessed anywhere in the program, protected allows the class to be accessed by itself and its subclasses, and private restricts access to the class itself.
    • As usual, a semicolon is required at the end of the class declaration.
  • In Java a subclass is defined with the following structure:

    accessSpecifier class SubClassName extends SuperClassName {
        code;
    }
    • extends is a special keyword in Java that is used to specify a subclass's superclass.
    • an access specifier is included before every Java class to indicate what other classes may access it.
  • It is important to note that every method that is accessible in the computer class, should be accessible in the laptop class. So laptop.access_internet(browser) should work just as well as computer.access_internet(browser).

Wednesday, January 11, 2012

Classes

A class is code containing attributes and methods that is used as a blueprint for creating objects. Objects are instances of the class, and therefore have a similar structure to the class. Classes can be created for any sort of object that you could possibly imagine.
For instance, a car class would have make, model, and color attributes, and it would have accelerate, turn, and brake methods.
A butterfly class would have species, color, and size attributes, and it would have fly and eat methods.
A light switch class would have a state attribute, and it would have turn on, turn off, and check state methods.

Classes
General Structure


class ClassName
    code


Python


class LightSwitch (object):
    """A virtual light switch"""
    def __init__ (self, state):
        self.state = state

    def turn_on ():
        self.state = on

    def turn_off ():
        self.state = off

    def check_state ():
        return self.state


C++


class LightSwitch
{
    private:
        bool state;

    public:
        LightSwitch (bool _state)
        void turn_on ();
        void turn_off ();
        bool check_state();
};

LightSwitch::LightSwitch (bool _state)

{
    state = _state;
}

void LightSwitch::turn_on ()
{
    state = on;
}

void LightSwitch::turn_off ()
{
    state = off;
}

bool LightSwitch::check_state ()
{
    return state;
}



Java


public class LightSwitch {

    private boolean state;

    public LightSwitch (boolean _state) {
        state = _state;
    }

    public void turnOn () {
        state = on;
    }

    public void turnOff () {
        state = off;
    }

    public boolean checkState () {
        return state;
    }

}


Constructors


A constructor is a special method used in classes to instantiate an object when it is first created. By convention, this is the first method that is defined in a class. In Python, the constructor class is called "__init__" and the first parameter is always "self" by convention. In C++ and Java, the constructor class is called whatever the class name is (so in this case the constructor is called "LightSwitch").

A constructor does not need any parameters to instantiate an object. This is a special case called a default constructor. If you include a default constructor then you define the class attributes, in addition to declaring them.

However, in most cases you will declare class attributes, and define them in the constructor through the constructor's parameters (such as, "state = _state").


  • In Python a class is defined with the following structure:

    class ClassName (baseClassName):
        code
    • As usual, the colon is essential to the definition.
    • The base class name is "object" unless you are using inheritance (to be explained in the next blog) 
    • Since variables do not have to be declared in Python, the keyword "self" is used to differentiate class variables from parameter variables. 
    • All class methods are defined within the class definition (using tabs to structure the definitions)
  • In C++ a class is declared with the following structure:

    class ClassName
    {
        code;
    };
    • It is important to include the semicolon at the end of any class declaration in C++.
    • Classes in C++ are private by default. This means that nothing in them is accessible from outside of the class without the public keyword.
    • In this particular example I defined the class's methods outside of the class declaration. If this is done then each method name needs to be preceded by the class name and two colons. 
      • The two colons together are defined as the scope operator, and it is essential to specifying which class the method belongs to.
  • In Java a class is defined with the following structure:

    class ClassName {
        code;
    }
    • Unlike C++, Java does not require a semicolon after class declarations.
    • Java is completely object oriented, so it is not possible to define a class's methods outside of the class declaration.
    • Other than those differences, class declarations are basically the same in C++ and Java.

Wednesday, December 14, 2011

Functions

A function is a block of code within a program that does performs one task when called and then returns control back to the main program. This is a form of abstraction that allows for the construction of code that is easier to understand and debug. For example, let's say I want to write a program that simulates doing laundry. The steps for doing laundry are:
  1) sort whites and colors
  2) put a load in the washer
  3) add detergent
  4) start the machine
  5) move the load to the dryer
  6) start the dryer
  7) remove clothes and fold/hang up

I could write a program that does all of this in sequence, or I could write a function for each step.

Functions
General Structure


    function name (parameters)
        code
        return statement


Python


    def sort_clothes (color):
        """Sort clothes into a white pile and a color pile"""
     
        if (color == "white"):
            return "whites"

        else:
            return "colors"


C++


    string sort_clothes (string color)
    {
        if (color == "white")
            return "whites";

        else
            return "colors";
    }


Java


    String sortClothes (String color) {
        if (color == "white")
            return "whites";

        else
            return "colors";
    }

  • In Python you have to include the def keyword in order to specify that you are writing a function.
    • You must include parenthesis even if you don't have any parameters.
          def sort_clothes():
              # code
    •  You must include a colon after the parameter list.
    • The sentence enclosed in triple quotes is a docstring (documentation string). This is Python-specific and is used to comment functions.
      • docstrings are not required, but they must be the first line in a function if they are included.
      • when running a program in IDLE (the Python GUI) docstrings pop up as you type your function call.
    • Just like with variables, you don't have to declare types when writing a Python function.
  • In C++ a function header includes the functions return type, the function name, and a parameter list.
    • the function's code is enclosed within curly braces
    • The C++ compiler needs to know about all functions that are going to be used. For this reason, you should either:
      •  define them at the top before your main method
      • or declare them at the top and define them at the bottom. A function declaration is the function header followed by a semicolon:

        string sort_clothes (color);
  • In Java functions are defined the same way as C++.
    • The only difference between the C++ and Java function here is the string class (which is capitalized in Java) and the naming convention (camel case instead of underscores).

Return Statements

You probably noticed that each function ends with a return statement. This is a statement specified by the return keyword and followed by a return value. Essentially, functions can be thought of as their return value.

So, you can think of:   sort_clothes ("blue")
as:                                "colors"

  • Once the function is called it is replaced with the return value.
  • Because functions are replaced with their return value, you can set a variable equal to a function call:

    String pile = sortClothes("red");
    System.out.println(pile);                    // should output "colors" to the console
  • Functions can only return one value at a time. If you're trying to return more than one thing, you probably need more than one function.
  • The only time you don't need a return statement is when a function's return type is void. The void return type can be used when you want to permanently modify the parameter sent in, or if you don't need to return a value.

    void print_message (string message)
    {
        cout << message << endl;             // should output the contents of message to the console
    }

Function Overloading

Function overloading is the defining of more than one function that have the same name, but different parameters. The parameters can vary by type or number. For example:

    int volume (int side)
    {
        cube_volume = side * side * side;
        return cube_volume;
    }

    int volume (int length, int width, int height)
    {
        rec_prism_volume = length * width * height;
        return rec_prism_volume;
    }

Both of these have the same name, volume. But for a cube you just need one parameter, whereas for a rectangular prism you need three parameters. There could be another function of the same name that uses a different definition of volume:

    int volume (char title)
    {
        if (title == "A" || "a")
            return 1;

        else if (title == "B" || "b")
            return 2;

        // etc to Z
    }

In this case we still return an integer, but this corresponds to which volume an encyclopedia reference book is. 

It is important to note that function overloading is dependent on parameters NOT the return type. The compiler doesn't know or care what the return type is when it is compiling. But it does look at the parameters.

Also, parameter overloading is found in both C++ and Java, but not officially in Python.

Tuesday, December 6, 2011

Data Structures: Arrays

A data structure is a way of storing and organizing data. There are many types of data structures, but the array is the most common. Arrays store variables of one data type, which can be accessed through indexing. Arrays are not formally supported in Python (however, there are many mutations based on arrays), so I will only go over arrays in C++ and Java.

Arrays
General Structure

  • Arrays can be defined and initialized in two ways:

          int prime_numbers [10];

          int prime_numbers [] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

  • In the first example the size is declared explicitly, and the data is added later (probably with a for loop). In the second example the size is declared implicitly by assigning ten data elements in curly braces.
  • In the first case the data elements can be set through indexing. The first data element in an array is always at index zero, so the last index is one less than the total number of elements:

          prime_numbers[0] = 2;
          prime_numbers[1] = 3;
          prime_numbers[2] = 5;
          (...)
          prime_numbers[9] = 29;


  • This can also be accomplished with a for loop:

          for (int n = 0; n < 11; n++)
         {
             prime_numbers[n] = next_prime_number;
         }


  • Data elements can be accessed similarly to how they are set:

          first_prime_number = prime_numbers[0];             // should equal 2




This is pretty much the extent of what the built-in array class can do in C++. There are more things that are possible in Java, but I'm going to wait until after I write about functions and classes to get into that.

There are also multi-dimensional arrays, which I will save until later as well.

Monday, November 14, 2011

Control Structures: For Loops

While loops are useful for executing a block of code until a boolean condition is met. Oftentimes this boolean condition involves counting or some type of iteration. For loops are a variation of while loops, which are used specifically for iteration.


For Loops
General Structure


    for (start condition, end condition, advancement condition)
        code runs


Python


    for number in range(11):
        print number


C++


    for (int number = 1; number < 11; number++)
    {
        cout << number << endl;
    }


Java


    for (int number = 1; number < 11; number++) {
        System.out.println(number);
    }


  • In Python you don't actually have to specify a start condition or an advancement condition because those are built into the code already. 
    • The word "number" is a variable name that can be replaced with anything without changing the loop's behavior. I could just as easily type any of the following:

      for x in range(11)
      for letter in range(11)
      for banana in range(11)

      It doesn't matter what word I put in that spot, the program will still iterate from 0 to 10.
  • In C++ and Java you have to declare the variable type, name, and value for the start condition.
    • Make sure to put a semicolon after the start condition and end condition. The conditions could also be written like this:

      for (int number = 0;
             number < 11;
             number++)

      But that isn't as compact, and it also veers from convention.
  • In any of these languages, you can iterate over anything that has index values. This includes, strings, arrays, lists, tuples, etc. (I will explain all of these later) In Python, for instance:

    username = aedunn
    for letter in username:
        print letter                        # should print "a e d u n n" (on separate lines)

Control Structures: While Loops

The if/else and switch statement control structures allows for selective code execution based on different choices. But what if you want to keep executing some code until a certain condition is met? For instance, let's say I want a job: While I don't have a job, I'll keep applying to jobs. When I get a job, I'll stop applying.
This is much easier than: While I don't have a job at McDonald's, I'll apply for another job. While I don't have a job at Google, I'll apply for another job/. While I don't have a job at some other place, I'll apply for another job, etc.
In case you haven't guessed yet, the while loop is the answer to this problem. While loops can be thought of as repeating if statements, but with a more general boolean condition.

While Loops
General Structure

    while (boolean condition)
        code runs
        code to check/advance condition


Python


    count = 1
    while (count < 11)
        print count
        count += 1


C++


    int count = 1;
    while (count < 11)
    {
        cout << count << endl;
        count++;
    }


Java


    int count = 1;
    while (count < 11) {
        System.out.println(count);
        count++;
    }


  • While loops will keep running until the boolean condition evaluates to true. It is VERY easy to get caught in an infinite loop if you forget to include a statement to advance/change the condition.
  • In Python, the indentation is necessary
    • Also, when iterating over numbers like in this example, Python has an included "range(stop)" function. To use it you just include the number you want it to iterate up to:

      range(10)                    # should print [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] to the screen

      You can also specify a start number and counting increment (the range function starts at 0 by default).

      range(2, 11, 2):           # should print [2, 4, 6, 8, 10] to the screen
  • In C++ and Java, the brackets are necessary for any code that exceeds one line. It's good habit to include them regardless.
    • Also, C++ and Java both support a variation of the while loop that executes the code at least once before it evaluates the boolean condition. This is the do while loop.

      Do While Loop
      Example in C++


      int count = 1;
      do {
             cout << count << endl;
             count++;
      }      while (count < 11);


    • Notice that there is a semicolon after the while boolean condition. This is the ONLY control structure that has a semicolon here. It is included due to the nature of the loop (evaluation after execution).

Tuesday, November 8, 2011

Control Structures: Switch

Another type of conditional statement is the switch statement. This is a variation of if/else statements, which is visually more compact and also allows for faster compilation.


Switch Statements
General Structure

    switch (expression)
    {
        case first-constant:
            code
            break

        case second-constant:
            code
            break

        default:
            code
            break
    }


Python

Python does not formally support switch statements. There are ways to emulate them, but I'll leave that for another discussion.


C++

    switch (month)
    {
        case 1:
            cout << "The month is January." << endl;
            break;

        case 2:
            cout << "The month is February." << endl;
            break;

        case 3:
            cout << "The month is March." << endl;
            break;

        case 4:
            cout << "The month is April." << endl;
            break;

        case 5:
            cout << "The month is May." << endl;
            break;

        case 6:
            cout << "The month is June." << endl;
            break;

        case 7:
            cout << "The month is July." << endl;
            break;

        case 8:
            cout << "The month is August." << endl;
            break;

        case 9:
            cout << "The month is September." << endl;
            break;

        case 10:
            cout << "The month is October." << endl;
            break;

        case 11:
            cout << "The month is November." << endl;
            break;

        case 12:
            cout << "The month is December." << endl;
            break;

        default:
            cout << "Invalid month." << endl;
    }


Java

    switch (month) {
        case 1:
            System.out.println("The month is January.");
            break;

        case 2:
            System.out.println("The month is February.");
            break;

        case 3:
            System.out.println("The month is March.");
            break;

        case 4:
            System.out.println("The month is April.");
            break;

        case 5:
            System.out.println("The month is May.");
            break;

        case 6:
            System.out.println("The month is June.");
            break;

        case 7:
            System.out.println("The month is July.");
            break;

        case 8:
            System.out.println("The month is August.");
            break;

        case 9:
            System.out.println("The month is September.");
            break;

        case 10:
            System.out.println("The month is October.");
            break;

        case 11:
            System.out.println("The month is November.");
            break;

        case 12:
            System.out.println("The month is December.");
            break;

        default:
            System.out.println("Invalid month");
            break;
    }

  • Once again, C++ and Java's syntax are remarkably similar. In fact, they are identical other than their print statements. Some things to note:
    • The cases are equivalent to if or else if, the default is equivalent to else.
    • The case expression supports more than just integers (it also supports integer variations and characters), but whatever is used must be a constant.
    • There is NO punctuation after the expression.
    • There is a colon after each case.
    • You also don't need to include the "break" statement under the "default" case since it's the end of the loop.
    • None of the whitespace is necessary. You could just as easily write each case like:
      case 1:    System.out.println("The month is January.");    break;
    • However, I chose to write the examples this way for readability.

Control Structures: If, Else

In a simple program each statement or expression is evaluated in sequence:
   
     username = "aedunn"
     password = "password"
     print "Welcome, aedunn!"

In this example (in Python), the variable name "username" is first assigned to the string "aedunn," then the variable name "password" is assigned to the string "password," and finally the string "Welcome, aedunn!" is printed to the screen. However, it might be desirable to be able to control whether a statement is run. This is possible through the use of control structures, which help direct the flow of program execution.

The first type of control structure I'll go over is conditional statements. These determine whether their corresponding code should execute based on a boolean condition: if the boolean condition is true, the code runs. If it is false, the code is skipped. The most common conditional statements are the if/else clauses.


If/Else
General Structure

    if (boolean statement)
        code runs

    else if (another boolean statement)
        code runs

    else
        code runs


Python


    if (username == "aedunn" and password == "password"):
        print "Welcome, aedunn!"

    elif (username == "aedunn" and password != "password"):
        print "Forgot your password?"

    elif (username != "aedunn" and password == "password"):
        print "Forgot your username?"

    else:
        print "Permission Denied!"

C++

    if (username == "aedunn" && password == "password")
    {
        cout << "Welcome, aedunn!" << endl;
    }

    else if (username == "aedunn" && password != "password")
    {
        cout "Forgot your password?" << endl;
    }

    else if (username != "aedunn" && password == "password")
    {
        cout << "Forgot your username?" << endl;
    }

    else
    {
        cout << "Permission Denied!" << endl;
    }


Java


    if (username == "aedunn" && password == "password") {
         System.out.println("Welcome, aedunn!");
    }

    else if (username == "aedunn" && password != "password") {
        System.out.println("Forgot your password?");
    }

    else if (username != "aedunn" && password == "password") {
        System.out.println("Forgot your username?");
    }

    else {
        System.out.println("Permission Denied!");
    }


  • In general, all three languages follow the same structure for if/else statements. However, Python is not as similar to C++ and Java as they are to each other
  • In Python, the colon after the boolean statement is necessary for the program to run
    • Also, the indentation is necessary as well to indicate that the code belongs to the conditional statement above it
    • Finally, in Python "else if" is shortened to "elif"
  • The only difference in if/else in C++ and Java is the print statement
    • There is NO punctuation after the boolean statement. (no semi-colon, no colon, NOTHING!)
    • Each conditional statement (if, else if, else) can control one line of code underneath it
    • If additional lines of code are required then you MUST include the brackets! Brackets are only necessary for more than one line of code, but I've included them here because it is good programming style to include them anyway (for better readability and so you don't get an error if you add another line of code and forget to add brackets).
    • Indentation is not necessary, but (once again) it improves readability.

    Monday, November 7, 2011

    Operators

    An operator is a symbol, which can be used to produce a new value from one or more input values. In programming there are seven main types:

    Assignment
    • The assignment operator (=) is used to assign a value to a variable. The value is on the right and the variable is on the left side of the assignment operator.
      • int letters = 26;

    Arithmetic
    Examples in Python
    • Arithmetic operators are used to perform calculations. In general, these are used the same as in mathematics.
    • The addition operator (+) is used to add two or more inputs.
      • sum = 3 + 5
      • print sum            # sum should equal 8
    • The subtraction operator (-) is used to subtract one or more inputs from another.
      • difference = 5 - 3
      • print difference   # difference should equal 2
    • The multiplication operator (*) is used to multiply one or more inputs.
      • product = 5 * 3
      • print product       # product should equal 15
    • The division operator (/) is used to divide one of more inputs from another.
      • quotient = 5 / 3
      • print quotient      # quotient should equal 1 because both numbers are integers. The result would be 1.6667 if floats were used (declared in Python by writing either of the numbers with a decimal: 5.0 / 3)
    • The remainder operator (%) or modulo is used to find the remainder of the division of inputs.
      • remainder = 5 % 3
      • print remainder    # remainder should equal 2

    Compound Assignment
    Examples in Python.
    • Compound assignment operators are shortcuts that allow you to perform a calculation and immediately assign the resulting value to a variable.
    • So instead of:
      • sum = 3 + 5
      • sum = sum + 2
    • You can do:
      • sum = 3 + 5
      • sum += 2
    • There is a compound operator for all of the normal arithmetic operators, including:
      • addition: +=
      • subtraction: -=
      • multiplication: *=
      • division: /=
      • modulo: %=

    Unary
    Examples in C++.
    • In C++ and Java there are even easier compound assignment operators for addition (++) and subtraction (--). These perform calculations and assign the result to variables or vice versa, depending on where they are placed:
              int x, y;
              x = 0;
              y = x++;                            // the unary addition operator is placed after the variable name
              cout << x << ", ";               // assignment to y occurs first, addition to x occurs second
              cout << y << endl;             // 0, 1 should print to the screen
              
             int x, y;
             x = 0;
             y = ++ x;                           // the unary addition operator is placed before the variable name
             cout << x << ", ";               // addition to x occurs first, assignment to y occurs second
             cout << y << endl;              // 1, 1 should print to the screen


    Equality and Relational
    Examples in Python.
    • These operators are used to determine the relationship between two operands.
    • Equals (==) determines whether the operands are equal
      • print 3 == 5               # should print 0 (for false)
      • print 3 == 3               # should print 1 (for true)
    • Does not equal (!=) determines whether the operands are not equal
      • print 3 != 5                # should print 1 (for true)
      • print 3 != 3                # should print 0 (for false)
    • Greater than (>) determines whether the first operand is greater than the second
      • print 3 > 5                 # should print 0 (for false)
      • print 5 > 3                 # should print 1 (for true)
    • Less than (<) determines whether the first operand is less than the second
      • print 3 < 5                # should print 1 (for true)
      • print 5 < 3                # should print 0 (for false)
    • Greater than or equal (>=) determines whether the first operand is greater than or equal to the second
      • print 3 >= 5              # should print 0 (for false)
      • print 3 >= 3              # should print 1 (for true)
    • Less than of equal (<=) determines whether the first operand is less than or equal to the second
      • print 3 <= 3              # should print 1 (for true)
      • print 5 <= 3              # should print 0 (for false)

    Logical
    Examples in C++.
    • Logical operators (related to Boolean logic) are used to evaluate the inverse of an expression or two expressions to obtain one result.
    • The NOT operator (!) is used to determine the inverse of an expression.
               bool a = true;
               result = !a;
               cout << result << endl;      // should print 0 (for false)

               bool a = false;
               result = !a;
               cout << result << endl;       // should print 1 (for true)
    • The AND operator (&&) is used to determine whether both expressions are true. 
               bool, a, b;
               a = true;
               b = true;
               result = a && b
               cout << result << endl;      // should print 1 (for true)

               a = true;
               b = false;
               result = a && b;
               cout << result << endl;       // should print 0 (for false)
    • The OR operator (||) is used to determine whether either expression is true.
               bool a, b;
               a = true;
               b = false;
               result = a || b;
               cout << result << endl;        // should print 1 (for true)

               a = false;
               b = false;
               result = a || b;
               cout << result << endl;         // should print 0 (for false)
    • note that these symbols are appropriate for C++ and Java. Python also supports logical operations, but !, &&, and || are replaced by the words "not," "and," and "or," respectively.

    Bitwise
    Examples are just binary numbers. They are NOT written in a language's syntax.
    • Underneath the surface, all computations in programming are done in binary. Occasionally it may be more useful to work directly in binary, so many languages support bitwise operations. There is some overlap between logical operations and bitwise operations, so these operators should look familiar.
    • The bitwise complement operator (~) is equivalent to the logical NOT. It is used to invert all of the bits of a binary number. (returns 1 if 0, returns 0 if 1)

      ~01001001
      ---------------
        10110110
    • The bitwise AND operator (&) is equivalent to the logical AND. It is used to determine whether both bits are true. (returns 1 only if both bits are 1, 0 otherwise)

          01110011
      & 10010110
      -----------------
          00010010
    • The bitwise OR operator (|) is equivalent to the logical OR. It is used to determine whether either bit is true. (returns 0 only if both bits are 0, 1 otherwise)

        11010110
      | 00100011
      ---------------
        11110111
    • The bitwise XOR (exclusive or) operator (^) is used to determine whether both bits are equal. (returns 1 if both 1 or both 0, returns 0 otherwise)

         11101100
      ^ 01010110
      ----------------
         01000101
    • The bitwise left shift operator (<<) is used to shift the bits a specified number left. Zeros are placed in the empty spaces created on the right side of the binary number. (numbers shifted out of the number in green, numbers that remain in blue, placeholder zeros in red)

      11010100 << 2
      --------------------
      01010000
    • The bitwise right shift operator (>>) is used to shift the bits a specified number right. Zeros are placed in the empty spaces created on the left side of the binary number. (numbers shifted out of the number in green, numbers that remain in blue, placeholder zeros in red)

      11010100 >> 2
      --------------------
      00110101