Discussion 10-20

While loops

Last time we learned about while loops. Today we talked about for loops and then did a bunch of examples with both kinds of loops. The syntax for a for loop is:

for ( INITIAL_STEP ; CONDITION ; END_OF_ITERATION_STEP ) {
    // Code here!
}

This code has the following effect:

  1. Run whatever statement is in the INITIAL_STEP slot.
  2. Check whether CONDITION is true. If so, go to step 3. If not, go to step 5.
  3. Execute the "Code here!" part, i.e. whatever code we put inside that set of curly braces.
  4. Execute whatever's in the END_OF_ITERATION_STEP slot. Then go back to step 2.
  5. Jump to the end of the "Code here!" section, i.e. just after the curly braces. Then continue executing the program like normal.

Technically, anything you do with a for loop could have been done with a while loop or vice versa. A good rule of thumb is, if you need to loop n times (where n is a number or variable) then I'd prefer a for loop. If you need to loop indefinitely until some more complicated condition is met, I'd prefer a while loop.

Thus if I need my loop to print 10 numbers, I would use for. If I need a loop that runs until the user says to stop (like the main loop in HW4), then I would use while.

Examples

The next two programs were written to solve problems from the Project Euler website. The comments in these programs explain what problem we're solving and also the basic approach we're going to take.

Google searches

Here are some Google searches you could try if you're having trouble with today's material. I'm deliberately trying to choose search terms that you could have thought of yourself!

Extra stuff to try for fun (not required)

Project Euler is a source for lots of cool problems! Some of them are too mathy, but a lot of the problems on there would be great programming practice for you guys. If you're looking for extra cool stuff to try, I'd definitely make an account and look around for problems that seem fun to you. I bet there are several that are both approachable and pretty cool! Now that you know loops, you guys can make your computers do way more awesome stuff than you could before.