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)

No comments:

Post a Comment