Monday, November 14, 2011

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).

No comments:

Post a Comment