Discussion 10-18

While loops

Loops let us write programs that will rerun certain pieces of the code several times. Today we talked about while loops. The syntax is:

while ( CONDITION ) {
    // Code here!
}

This code has the following effect:

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

This is actually incredibly powerful and it will allow us to do way more crazy stuff with our programs than we could before! We spent most of today's class setting up a few examples:

Examples

counting.cpp is a simple program that asks for two numbers, and then "counts" from the first input number to the second. We tried some variations and attempted to predict the output for each version. For example, try inputting 3 6 vs 14 9 vs -3 -3.

computeSum.cpp is a simple program that asks the user to type as many integers as they want, and then outputs the sum of the inputs. The user signals that they're done typing by inputting the integer 0.

computeLargest.cpp is similar in structure to the previous example. This time we ask the user to type as many POSITIVE integers as they want, and then we output the largest of the integers they typed. Again, the user signals that they're done typing by inputting 0.

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!