Showing posts with label control structures. Show all posts
Showing posts with label control structures. Show all posts

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.