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

    Saturday, November 5, 2011

    Variables and Data Types

    Variables in programming have five attributes:

    1. Name: A variable's name is linked to information. A descriptive name makes code easier to understand by other programmer's or even by you in the future.
    2. Type: The kind of information that is linked to the variable name. (See discussion of data types below)
    3. Value: The actual information stored.
    4. Scope: Where in a program a variable can be used. (to be discussed with functions)
    5. Lifetime: When the variable exists during each run of the program. (to be discussed with functions)

    Python

    factor1 = 3
    factor2 = 5
    quotient = factor1 * factor2

    OR

    quotient = 3 *5


    C++

    int factor1, factor2, quotient;
    factor1 = 3;
    factor2 = 5;
    quotient = factor1 * factor2;

    OR

    int factor1 = 3;
    int factor2 = 5;
    int quotient = factor1 * factor2;

    OR

    int quotient = 3 * 5;


    Java

    int factor1, factor2, quotient;
    factor1 = 3;
    factor2 = 5;
    quotient = factor1 * factor2;

    OR

    int factor1 = 3;
    int factor2 = 5;
    int quotient = factor1 * factor2;

    OR

    int quotient = 3 * 5;

    • When doing math with any of the languages you can either define variables for each number and then define another variable, which uses those variables to actually do the calculations, or you can define a variable by doing the calculations immediately.
    • In Python, type declarations are unnecessary. Unfortunately, this makes it impossible to declare a variable before you define it.
    • In both C++ and Java there are a few ways declare and define variables:
      • you can declare all of your variables first and then define them individually before doing the calculations.
      • you can define each variable as you declare it before doing the calculations.
      • or you can define a variable at declaration with the calculations.

    Data Types:
    since variables don't need to be declared in Python, all example declarations are applicable to only C++ and Java.

    Every programming language has built-in data types that allow you to perform various tasks. Primitive data types are found in most languages. These include:

    Numbers
    • Integer: Integers are whole numbers without decimal places. They are usually a sufficient size for whatever data manipulation needs to be accomplished, but they can lead to integer overflow in some situations.
      • int twenty = 20;
    • Short (integer): Shorts are the smallest integer variation in most languages. They are used when it is necessary to save memory
      • short two = 2;
    • Long (integer): The long is a longer variation of the integer. They are used when an integer would lead to overflow.
      • long two_hundred = 200L;
    • Float: Floats are decimal numbers that can contain approximately 7 digits. 
      • float decimal_two = 2.0341f;
    • Double: Doubles are a double precision float. They can contain approximately 15 digits (rather than only 7).
      • double pi = 3.14159265;
    Other
    • Boolean: Boolean values are either true or false. They can be used to track conditions (whether the condition is true or false).
      • bool contains_letters = 1;
      • 1 = true, 0 = false
    • Character: Characters are just a single character.
      • char a_letter = 'A';
      • characters must be declared in single quotes
    There are other data types as well, but they vary by language. For example, in Python strings (a sequence of characters) are an included data type. In Java, the byte (a variation of the integer, which is even smaller than a short) is a primitive data type.

    Thursday, November 3, 2011

    Hello World!

    The first things most people who are just learning programming do is the pervasive "Hello World!" program. This short program's prevalence is so extensive because it demonstrates a language's structure and syntax. Specifically it shows how to print something to the screen and how to run a program.

    Python


    print "Hello World!"


    C++


    #include <iostream>
    using namespace std;

    int main()
    {
        cout << "Hello World!" << endl;
    }


    Java


    class HelloWorld {

        public static void main(String[] args) {

            System.out.println("Hello World!");
        }

    }

    • As you can see, Python's syntax is the simplest. There is no necessary structure, and all you have to do is type "print [thing to be printed (in single or double quotes)]"
    • C++'s syntax is more complicated, but it is by no means convoluted. 
      • In order to use cout (the C++ equivalent of print) you must include the iostream library. 
      • However, just including the library isn't enough. You have to tell the pre-processor which part of iostream it needs to look in to use cout. This is why we include the "using namespace std;" line. 
      • Finally, because C++ is an object-oriented program, every script you write must have a main function.  The convention is for main to have a return type of int and for all of the Also, every functions' code is contained within curly braces.
    • Java is based on C++, so it has a lot of the same conventions (such as ending every statement in a semi-colon). However, it is even more object-oriented (in that every script is a class, which creates an object when compiled). 
      • Because everything in Java is a class, everything that can be done in Java is accomplished through method calls to a class.
      • When printing, System is a class (first letter is upper case and multiple words written with camel case by convention), which contains an out method and a println method.
      • You'll recognize that main is still required, but now you have to declare it with public, static, and void, rather than just int. It also contains two parameters: String[] and args. 

    Starting out with...

    In order to get started with programming you have to have the correct tools. So here is a step-by-step guide to getting started with Python, C++, and Java for Linux, Windows, and Mac.

    • Linux: If you have a version of Linux on your computer then, congratulations! You probably already have everything you need installed. All you have to do is verify that some version of Python 2 is included with your OS. If for some reason Python is not included, just apt-get install, yum install, or zypper through terminal.
    • Windows/Mac: You can find an installer on Python's official website. Just click on the correct link (I'll be using the syntax for Python 2) and install like any other software. http://www.python.org/getit/
    • Compiling: Since Python is an interpreted language you don't need a compiler. 
    • Running: All you have to do to run a program is cd to the appropriate directory through terminal and then type "python [program name].py"
    • Linux: Once again, congratulations! Everything you need to run C++ is probably already on your computer. You'll need a text editor and a compiler. You can use any test editor you prefer, but emacs seems to be the top choice for C++ editing. The C++ compiler is g++. If either one of these is missing then just install them the usual way from terminal.
    • Windows: A popular option for windows users is Microsoft's Visual C++, which is a nice GUI that combines text editing and compiler. Visual C++ can be installed here: http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express
      Another option for the windows user is Cygwin, which can be used to create C++ in a Linux-like environment. Cygwin can be installed here: http://www.cygwin.com/
    • Mac: You can download XCode from the app store, which should have everything you need. For text editing, Macs come with text edit and text wrangler or you can download aquamacs (a Mac version of emacs) here: http://aquamacs.org/
    • Compiling: cd to the appropriate directory through terminal and type "g++ [program name].cpp" OR "g++ -o [output file name] [program name].cpp"
      g++ tutorials: http://pages.cs.wisc.edu/~beechung/ref/gcc-intro.html AND http://myweb.stedwards.edu/laurab/help/g++help.html
    • Running: With the first compilation just type "./a.out" OR with the second method type "./[output file name]"

    • Linux: You'll need to download the Java JDK package, which can be done the usual way through terminal. (it may be named OpenJDK). You can use any text editor
    • Windows/Mac: download the Java JDK packager here: http://www.oracle.com/technetwork/java/javase/downloads/index.html
      You can use any text editor, but a popular GUI choice is BlueJ, which can be downloaded here: http://www.bluej.org/
    • Compiling: cd to the appropriate directory through terminal and type "javac [program name].java" (make sure that the program name matches the class name that is in your code, otherwise you'll get an error) This will create a class file of the same name as your java file.
    • Running: type "java [program name]" (without an extension)
    So you should be all set to start programming! Of course, if you have no experience then you'll probably appreciate some tutorials. The official websites for all three languages are very informative, and are a good place to start.

    Java: http://download.oracle.com/javase/tutorial/java/index.html

    NOTE: I will be using coding comments in some of the examples to explain what I'm doing, or to tell you what the output should be. In Python a comment is indicated by a hashtag/octothorpe/pound sign (#). In C++ and Java a single line comment is indicated by two forward slashes (//). A multiple line comment is started with a forward slash, followed by an asterisks (/*) and ended with an asterisks, followed by a forward slash (*/).

    A Quick Comparison of Python, C++, and Java

    There are a plethora of programming languages out there. I'm only going to focus on three: Python (because it was the language I learned to program in, and I love its simplicity and strength), C++ (because it was the second language I learned and it's a big player in the software development world), and Java (because it is another key player for software development, especially for mobile apps).


    Before I begin comparing each language's syntax I'd like to explain a little bit of what makes them inherently different. To do this, I'll introduce a few of the programming paradigms that are available.
    A programming paradigm is a model or pattern used for problem-solving. There are two main types:
    1. Functional Programming relies on the application of functions. Purely functional languages, like Lisp, Scheme, and Racket are very action-oriented. Python and C++ both support functional programming.
    2. Object-Oriented Programming (OOP) relies on the use of objects, which consist of data (variables) and methods (functions). Most languages support OOP, including Python and C++, but Java is composed entirely of classes and objects and it is very noun-oriented.
    However, there are many other paradigms, including: imperative, procedural, and generic.


    In addition to its paradigm, a language is also classified based on its compiler support. There are two main types for this as well:
    1. Compiled Languages translate source code into machine code before they can be run. Any language that must be compiled before it can be run falls into this category. C++ and Java are both compiled languages.
    2. Interpreted Languages, on the other hand, can be executed directly from the source code without being compiled. Python is an interpreted language.