6: Loops

General Information

Housekeeping

Announcements

See Announcements link in Canvas to keep up with what is going on. Here are a few for review:

Questions from last class or reading?

Homework Questions?

Learning from the Exam

Learner Outcomes

At the end of the lesson the student will be able to:

  • Know what was missed on the midterm
  • Decide on what to do to improve performance as needed

6.1.1: Post Exam Review

6.1.2: Post Exam Survey

6.1.3: Making the Grade

Suggestions for Improving your Grade

Exercise 6.1: Exam Self-Reflection

In this exercise we reflect on our progress in this course.

You Can Learn Anything: from the Khan Academy (1:30)

Reflection (3m)

  1. Find something to write or type on.
  2. Reflect on the following questions and write down an answer for yourself:
    1. Are you achieving your goals for this course?
    2. What ways can you think of to improve your progress towards goals?
    3. What actions are you going to take to better meet your goals?

More Information

6.2: Cooperative Quizzes

Quiz Part 1: Individual Readiness Assessment

Quiz Part 2: Team Readiness Assessment (15m)

Quiz Appeals

6.3: While Loops

Reviewing while loops

CA 6.3: Coding Challenge Questions

Any problems with any of these Coding Challenges? (Zybooks sign in)

If so, list the CA numbers in Chat

Exercise 6.3: Repeating a Program (10m)

In this exercise we use a loop to allow a user to repeat a program.

Remember to verify your code by compiling after each step.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following program into a text editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        int guess = 0;
        cout << "I'm thinking of a number between"
             << " 1 and 10.\nCan you guess it?\n\n"
             << "Enter your guess: ";
        cin >> guess;
    
        if (7 == guess) {
            cout << "*** Correct! ***\n";
        } else {
            cout << "Sorry, that is not correct.\n";
            cout << "Try again.\n";
        }
        return 0;
    }
    
  2. Add the following code after the statement int guess = 0; and before the cout statement:
    char repeat = 'y';
    

    This is the initialization code that we will use for the test condition that comes next.

  3. We want to repeat all the rest of the code in our program. For this we need to add a while statement such as:
    while ('y' == repeat) {
        // Place the rest of the code after the initialization
        // and before the return 0 between these curly braces.
    }
    

    Statements inside the curly braces repeat while the test condition in the parenthesis, ('y' == repeat), evaluates to true. For more information, see the textbook section on while loops.

  4. Inside the while loop we need some way to change the test condition. We change the test condition by letting the user enter a value for the repeat variable by adding the following code at the end of the loop just before the closing curly brace:
    cout << "\nDo you want to play again (y/n)? ";
    cin >> repeat;
    

    Without these two statements our loop would have no way to exit. A loop with no way to exit is known as an infinite loop. For more information, see the textbook section on while loops.

  5. Formatting a loop is important. Indent all the code within the curly braces of the while loop. For more information, see the textbook section on Style guidelines.
  6. As a final part of our program, we add the infamous phrase: "Game Over". Add the following statement after the closing curly brace of the while loop:
    cout << "Game over\n";
    
  7. Compile and run your program again and verify the output looks like:
    I'm thinking of a number between 1 and 10.
    Can you guess it?
    
    Enter your guess:  3
    Sorry, that is not correct.
    Try again.
    
    Do you want to play again (y/n)?  y
    I'm thinking of a number between 1 and 10.
    Can you guess it?
    
    Enter your guess:  7
    *** Correct! ***
    
    Do you want to play again (y/n)?  n
    Game over
    
  8. Once satisfied with your code, copy it into a text editor, save the file as "loopy.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

6.4: For Loops

A series of steps

Reviewing for Statements

Counter-Controlled-Loop Example

counting loop

Diagram of for Loop Operation

for loop flow chart

Execution Steps

           ❶    ⇛    ❷   ⇚   ❹
for (int i = start; i < end; i = i + 1) {
    ... ❸
}
❺
  1. When for loop is reached, execute the initialize statement (example: int i = 0;)
  2. Check if condition is true (example: i < 10;)
    1. if true then continue with Step 3
    2. Otherwise, continue with Step 5
  3. Execute the block containing the statements to repeat (body)
  4. When end of loop body is reached, execute the update statement (example: i = i + 1) and return to Step 2
  5. Loop is finished: continue with statements after the loop

CA 6.4: Coding Challenge Questions

Any problems with any of these Coding Challenges? (Zybooks sign in)

If so, list the CA numbers in Chat

Exercise 6.4a: Counting Loops (10m)

In this exercise we write a for-loop.

Remember to verify your code by compiling after each step.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following program into a text editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. Add the following code to get the maximum number from the user:
    int max = 0;
    cout << "This program writes lists of numbers.\n";
    cout << "Enter the maximum number: ";
    cin >> max;
    
  3. Add the following for-loop code to the main() function.
    cout << "for loop:\n";
    for (int i = 0; i < max; i++) {
        cout << i + 1 << endl;
    }
    
  4. Compile and run your code to verify it works. Does it start and stop with the correct numbers?
    This program writes lists of numbers.
    Enter the maximum number: 7
    for loop:
    1
    2
    3
    4
    5
    6
    7
    
  5. Once satisfied with your code, copy your code into a text editor, save the file as "forloop.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

Exercise 6.4b: Counting Down (10m)

In this exercise we look at how to count down with a for-loop instead of up.

Imagine we are at NASA Mission Control and a new space ship is about to be launched. We are going to write a program to count down from 10 to liftoff like this example.

NASA Mission Control readying for liftoff.
Initializing countdown from 10...
10
9
8
7
6
5
4
3
2
1
We have liftoff!

Thus we will need our loop to count down rather than up.

Remember the execution steps of a for-loop:

           ❶      ⇛      ❷     ⇚     ❹
for (int i = start; test condition; update statement) {
    ... ❸
}
❺

To solve this exercise we need to ask ourselves these questions:

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following program into a text editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. Add the following statement after the start of main():
    cout << "\nNASA Mission Control readying for liftoff\n";
    
  3. After the above cout statement, add other cout statements to duplicate the example output:
    NASA Mission Control readying for liftoff.
    Initializing countdown from 10...
    
  4. After the cout statements, write a for-loop from the following by filling in the needed parts:
    for (int countdown = 10; test condition here; update statement here) {
        // countdown statements here
    }
    

    What should go inside the test condition? countdown > 0

  5. Inside the for-loop, add a cout statement to print the value of countdown on its own line.
  6. When the loop is finished, add the final line:
    We have liftoff!
    
  7. Once satisfied with your code, copy your code into a text editor, save the file as "countdown.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

6.5: Loops and Strings

Reviewing Loops and Strings

Exercise 6.5: Iterating Strings (10m)

In this exercise we iterate a string.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following program into a text editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. Add the code to prompt for and read a messages from the user:
    cout << "Enter a word: ";
    string msg;
    cin >> msg;
    
  3. Next add the following for-loop code to the main() function.
    for (unsigned int i = 0; i < msg.size(); i++)
    {
        cout << i << ": " << msg.at(i) << endl;
    }
    
  4. Compile and run your code. What do you see when you compile and run?
    Enter a word: Hello!
    0: H
    1: e
    2: l
    3: l
    4: o
    5: !
    
  5. Once satisfied with your code, copy your code into a text editor, save the file as "letters.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

6.6: Nested Loops

Reviewing Nested Loops

CA 6.6: Coding Challenge Questions

Any problems with any of these Coding Challenges? (Zybooks sign in)

If so, list the CA numbers in Chat

Exercise 6.6: Nesting Loops (15m)

In this exercise we explore nested loops.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following program into a text editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        int num = 0;
        cout << "Enter a number: ";
        cin >> num;
        cout << endl;
    
        return 0;
    }
    
  2. Next we draw a simple bar chart for the number. Write a for-loop that counts from 0 to num and prints a single '*' each iteration of the loop. Use the name inner for the counting variable:
    for (int inner = 0; inner < num; inner++) {
        cout << '*';
    }
    
  3. After the closing brace of the for-loop, add a cout statement to print a newline character.
  4. When run, the program output should look like:
    Enter a number: 5
    *****
    

    Where 5 is the number entered by the user, shown in aqua italics for emphasis.

  5. Now we want to add an outer for-loop around the existing inner loop and both cout statements as follows:
    for (int outer = 0; outer < num; outer++) {
        for (int inner = 0; inner < num; inner++) {
            cout << '*';
        }
        cout << endl;
    }
    
  6. With the added outer loop, program output should look like:
    Enter a number: 5
    *****
    *****
    *****
    *****
    *****
    

    Where there are num line of num '*' characters.

  7. To make a triangle shape instead of a rectangle, we add an if-statement to the inner loop:
    if (inner <= outer) {
        cout << '*';
    }
    
  8. With the added if statement, program output should look like:
    Enter a number: 5
    *
    **
    ***
    ****
    *****
    
  9. To make a hollow shape, we add more conditions and clauses to if-statement of the inner loop:
    if (inner == 0 || outer == inner || outer == num - 1) {
        cout << '*';
    } else {
        cout << ' ';
    }
    
  10. Compile and run your program again and verify the output looks like:
    Enter a number: 5
    *
    **
    * *
    *  *
    *****
    
  11. Once satisfied with your code, copy your code into a text editor, save the file as "nested.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.