5: Getting Loopy

What We Will Cover


Continuations

Questions from last class?

Homework Questions?

Homework Discussion Questions (Wed/Thur)

  1. Did anyone use pair programming?
  2. What are the rules of pair programming?

Review Question

  • What is displayed by running the following code snippet?
    bool bb;
    if (bb || !bb) {
        cout << "That is the question!";
    }
    
    1. That is the question!
    2. Nothing
    3. Does not compile
    4. Compiles but causes an error when it runs

5.1: Counting Loops

Learner Outcomes

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

  • Design and implement counting loops
  • Apply counting loops to solve a number of problems
  • Translate these designs into C++ code

5.1.1: Using Loops to Count

  • Counting is a way to solve many programming problems
  • As an example, assume we want a program to write a list of numbers
  • We want to start at the number 1 and let the user choose the ending number
  • Thus the program output will look something like:
    This program writes lists of numbers.
    Enter the maximum number: 5
    1
    2
    3
    4
    5
    
  • We cannot simply print five numbers with cout because the user chooses the maximum number
  • Since we understand our problem, our next step is to write our algorithm
  • To help us understand the algorithm we try out some counting examples

Activity: Exploring the Problem

  • Clap your hands 5 times.
  • True or false: as you are clapping, you are repeating an action.
  • You know when to stop clapping because you ________.
  • True or false: as you are counting, you are testing the count against the number 5.
  • Every time you clap, you update the count by ________.

Developing the Algorithm

  • As we are clapping our hands, we are repeating an action
  • In C++, the control structure we have learned for repeating commands is the ________
  • To have a computer remember a number for the count, we declare a ________
  • After we declare a variable for counting, an appropriate initial value is ________
  • The while loop has a test condition as part of its syntax
    while (test) {
       statement1
       statement2
       ...
    }
    
  • If the count started at one, an appropriate test condition for the while loop to end after 5 iterations is ________
  • Every time we clapped our hands, we increase the count by one
  • A C++ statement to increase the count by one is ________
  • Thus for counting to 5, we have a series of commands like:
    int counter = 1;
    while (counter <= 5) {
        cout << counter << endl;
        counter++;
    }
    
  • If we allow the user to choose the ending number, what change do we make to the above loop?

Example C++ Application That Counts to a Number

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main() {
    int max = 0;
    cout << "This program writes lists of numbers.\n";
    cout << "Enter the maximum number: ";
    cin >> max;

    int counter = 1; // initialization code (1)
    while (counter <= max) // loop condition (2)
    {
        // loop body (3)
        cout << counter << endl;
        counter++; // update the counter (4)
    }

    return 0;
}
  • Notice there are four parts to a counting loop:
    1. initialization statement
    2. test condition
    3. loop body containing statement to repeat
    4. update statement
  • We need to remember these four parts when designing a counting loop

Difference Between Declaration and Initialization

  • Declaration means to set aside memory space
    int counter;
    
  • Initialization means set a value appropriate to the start of an operation
    counter = 1;
    
  • We often both declare and initialize a variable in one statement like:
    int counter = 1;
    

Check Yourself

  1. For the example loop shown below, the loop displays the numbers: ________.
    int counter = 1; // counter variable initialization
    while (counter <= 3) { // test condition
        //loop body containing statements to repeat
        cout << counter << endl;
        counter = counter + 1; // update statement
    }
    
  2. True or false: the purpose of the variable counter is to keep track of the number of repetitions.
  3. True or false: if counter started at 100 (counter = 100), the loop would never repeat.
  4. True or false: if the statement updating the count was omitted, like in the code shown below, the loop would never stop repeating until the program was terminated.
    int counter = 1; // counter variable initialization
    while (counter <= 5) { // test condition
        //loop body containing statements to repeat
        cout << counter << endl;
    }
    

A series of steps

5.1.2: Introducing for Statements

  • It turns out that counting is a very common way to use loops
  • Loops that are controlled by a counter variable are called counter-controlled loops
  • We can visualize a counter-controlled loop as a series of steps to reach a goal
  • A counter-controlled loop has the form:
    i = start;
    while (i < end) {
        ...
        i++;
    }
    
  • Where:
    • i: the name of a counter variable
    • start: the initial starting count
    • end: the final ending count
  • Because counting loops are so common, there is a special statement:
    for (i = start; i < end; i++) {
        ...
    }
    
  • The following example shows the same loop as before but using a for loop instead of a while loop
  • Note how the repeated code is indented inside the loop
  • This lets us see easily which code is repeated and which is not

Counter-Controlled-Loop Example

counting loop

Diagram of for Loop Operation

for loop flow chart

Execution Steps

  1. When for loop is reached, execute the initialize statement (example: int i = 1;)
  2. Check if condition is true (example: i <= max;)
    1. if true then continue with Step 3
    2. Otherwise it is false so continue with Step 6
  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)
  5. Return to Step 2
  6. Loop is finished: continue with statements after the loop

Exercise 5.1a: First for-Loop (5m)

In this exercise we write our first for-loop.

  1. Copy the following program into a text editor, save it as forloop.cpp, and then compile and run the starter program to make sure you copied it correctly.
    #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 << endl;
    }
    
  4. Compile and run your code to verify it works. Does it start and stop with the correct numbers?
  5. Save your final counting.cpp file to submit to Canvas as part of assignment 6.
  6. Be prepared to answer the following Check Yourself questions when called upon.

Check Yourself

Note: this loop is different than the previous exercise.

counting loop

  1. In the loop above, the initialization statement is ________.
    1. int i = 1
    2. i <= max
    3. i++
    4. cout << i << endl;
  2. For the same loop, the test condition is ________.
    1. int i = 1
    2. i <= max
    3. i++
    4. cout << i << endl;
  3. For the same loop, the update statement is ________.
    1. int i = 1
    2. i <= max
    3. i++
    4. cout << i << endl;
  4. For the same loop, if the user enters 3 the values printed are ________.
    1. 0, 1, 2, 3, 4
    2. 1, 2, 3, 4
    3. 0, 1, 2, 3
    4. 1, 2, 3
  5. For the same loop, if the user enters 3 the values of the counting variable i are ________.
    1. 0, 1, 2, 3, 4
    2. 1, 2, 3, 4
    3. 0, 1, 2, 3
    4. 1, 2, 3

5.1.3: Summing Numbers

  • One common looping task is to sum a series of numbers and calculate their sum
  • This is a mathematical operation known as summation

    Summation form 1 to n

  • For example, if we want to add the sum of the first four integers:
    sum = 1 + 2 + 3 + 4 = 10
  • As another example, we can add a list of 5 numbers:
    sum = 1 + 2 + 3 + 4 + 5 = 15
  • We want the user to specify n, which is the ending number

Developing the Algorithm

  • Looking at the examples above, what characteristics do we notice?
  • Do we see repetition? (Yes / No)
  • Whenever we need to sum a list of numbers, coding a loop is a good approach
  • For our loop we need to consider four parts:
    1. initialization statement
    2. test condition
    3. loop body containing statement to repeat
    4. update statement
  • In addition, we need to ask the user for n, the ending number
  • Thus our algorithm looks like:
    Prompt the user
    Get the ending number
    sum = 0
    for (int i = 1; i <= ending number; i++)
        sum = sum + i
    
  • Notice that we have a separate variable to store the sum
    sum = 0;
    
  • We need two variables in a summation loop
    • i: the counter variable to store the current count
    • sum: the variable to store the sum of the numbers

Example Application to Sum a Sequence of Numbers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main() {
    cout << "Enter the number to sum to: ";
    int endN = 0;
    cin >> endN;
    int sum = 0;
    for (int i = 1; i <= endN; i++) {
        sum = sum + i;
    }
    cout << "Total sum = " << sum << endl;

    return 0;
}

Variations

  • Sometimes we only want to sum part of the numbers in a loop
  • We can adjust the summing loop to read a different quantity of readings by changing the starting or ending value
  • For example, if we wanted to skip the first value we would change the for-loop like:
    for (int i = 2; i <= endN; i++)
    
  • We could change the summing loop to read every other value by changing the update statement like:
    for (int i = 2; i <= endN; i += 2)
    
  • What numbers does the above loop tally?
  • The starting value can have a significant effect on the loop
    for (int i = 1; i <= endN; i += 2)
    
  • What numbers does the above loop tally?
Be the computer

Be the computer

Tracing a Loop

  • To understand what is happening with these loops it is important to trace iterations
  • In essence, we must "be the computer" and follow it execution path
  • The counting variable is used by the computer to track the number of iterations
  • Thus a good technique is to keep track of the counting variable to understand the loop
  • In addition, we want to keep track of any other variable processed inside the loop
  • For example, with the following loop we would want to track the variables: sum, i, and reading:
    double sum = 0.0;
    for (int i = 0; i < 5; i++) {
      sum = sum + i;
    }
    
  • Thus we would write out headings for each value and update the variables for each pass of the loop
    sum   i
    ---   -
    0     0
    0     1
    1     2
    ...
    

Try It: Tracing a Loop (4m)

In this activity, we manually trace the execution of the following summing loop. This is a different loop than the previous examples.

const int END = 10;
int sum = 0;
for (int i = 1; i <= END; i += 2) {
    sum = sum + i;
}
  1. Take out a piece of paper and put your name on the paper.
  2. On the paper, add two columns for the two variables:
    sum     i
    ---     -
    
  3. Under each column, write the value of the sum followed by counter variable i that would be present when the test condition is checked for each iteration of the summing loop, like:
    sum     i
    ---     -
    0       1
    1       3
    (next pair of values)
    (next pair of values)
    ...
    

    Place each pair of values on a new line.

  4. Save your paper for a later exercise.
  5. Be prepared to answer the following Check Yourself questions when called upon.

Check Yourself

int sum = 0;
for (int i = 1; i <= 5; i++) {
    sum = sum + i;
}
  1. True or false: summing numbers in a loop requires a dedicated variable to store the sum.
  2. In the above loop, to sum even numbers only we would change the ________ statement.
  3. To sum odd numbers only, we would additionally change the initialization statement to start at ________.
  4. To compute the product of the numbers, we would change the update statement to use the operator ________?

5.1.4: Summing and Averaging

  • We have looked at adding the counter each time through a loop
  • Instead of just adding the counter each time, we can ask the user for each number and add it to the sum, like:
    sum = 0
    cin >> number;
    sum += number;
    cin >> number
    sum += number
    repeat for n numbers
    
  • We want to be able to sum any list of numbers
  • Whenever we need to sum a list of numbers, coding a loop is a good approach
  • If we know the number of inputs in advance, we can use a counting loop
    cout << "Enter the quantity of numbers: ";
    cin >> qty;
    for (int i = 1; i <= qty; i++)
    
  • Inside the loop we ask for each value and add it to the sum
    cout << "Enter value #" << i << ": ";
    double value;
    cin >> value;
    sum = sum + value;
    

Example Application to Sum a Series of Numbers Entered by a User

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main() {
    cout << "Enter the quantity of numbers: ";
    int qty = 0;
    cin >> qty;
    double sum = 0;
    for (int i = 0; i < qty; i++) {
        cout << "Enter value #" << (i + 1) << ": ";
        double value;
        cin >> value;
        sum = sum + value;
    }
    cout << "Total sum = " << sum << endl;

    return 0;
}

Calculating the Average

  • One we have the sum, we can calculate the average of a group of numbers
  • By average, we are referring to the statistical mean
  • To find a mean, we adding up the values and then divide by the number of values, like:
    cout << "Average = " << sum / qty << endl;
    

Check Yourself

double sum = 0;
for (int i = 1; i <= 5; i++) {
    cout << "Enter value #" << (i + 1) << ": ";
    double value;
    cin >> value;
    sum = sum + value;
}
  1. In the above loop, if the user enters the numbers 1, 2, 3, 4, 5 the value of sum after the loop finishes executing the sum is ________.
  2. After the above loop completes, the correct statement to average the input is ________.
    1. int average = sum * 5;
    2. double average = sum / 5;
    3. int average = sum / 5.0;
    4. double average = sum * 5.0;
  3. True or false: if sum was declared as an int, an average would still be accurate because decimals have little value.

5.1.5: More Loopy Errors

  • A common problem with counting loops is the off-by-one error
  • Finding the correct upper and lower bounds can be confusing
    • Should we start at 0 or 1?
    • Should we use < or <= as the test condition?
  • To understand the counting loop we need to count iterations
  • For instance, the following loop executes b - a times:
    for (int i = a; i < b; i++)
  • However, the following loop is executed b - a + 1 times:
    for (int i = a; i <= b; i++)
  • The "+1" is the source of many errors
  • As a test, to sum the numbers from 1 to 5 what is wrong with:
    #include <iostream>
    using namespace std;
    
    int main()
    {
        int sum = 0;
        for (int count = 0; count < 5; count++)
        {
            sum += count;
        }
        cout << sum << endl;
    
        return 0;
    }
    
  • One way to visualize the "+1" error is by looking at a fence

    Fenceposts in a fence

  • How many posts do we need for a fence with three sections? (answer)
  • It is easy to be "off-by-one" with problems like this
  • Forgetting to count the last value is sometimes called a fence-post error

Debugging Technique: Tracing Variables

  • One good way to discover loopy errors is to display the variables that are part of the loop
  • Tracing variables means watching their values change as the program executes
  • We can insert temporary output statements in a program to watch the variables, like:
    cout << "count=" << count << ", sum=" << sum << endl;

Check Yourself

  1. True or false: to avoid off-by-one errors, you need to count iterations.
  2. For three sections of fence you need ________ posts.
  3. The following loop executes ________ times.
    for (int i = a; i < b; i++)
    
    1. b + a
    2. b - a
    3. b - a + 1
    4. b - a - 1

Exercise 5.1: Count Down (5m)

In this exercise we continue exploring uses of counter-controlled loops.

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.

Specifications

  1. Copy the following program into a text editor, save it as countdown.cpp, and then compile and run the starter program to make sure you copied it correctly.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. In your countdown.cpp file, add a statement after your previous code like:
    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 that looks like this:
    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. Save your final countdown.cpp file to submit to Canvas as part of assignment 6 along with forloop.cpp.

When finished, please help those around you.

5.1.6: Summary

  • Loops allow us to repeat statements in a program
  • One common use for loops is to count
  • When counting, we need to remember the number of the count
  • To remember a value, we use a variable
  • Thus, to count, we need both a loop and a counter variable
  • The for loop gives us a compact way to code program counter-controlled loops
               ❶    ⇛    ❷   ⇚   ❸
    for (int i = start; i < end; i = i + 1) {
        ...
    }
    
  • The for-loop executes as shown in the following diagram:

    for-loop flow diagram

  • We saw several applications for loops that count in this section:
    • Counting loops
    • Summing numbers
    • Averaging numbers
  • Once we know that a program needs a loop, we need to consider these things:
    1. Loop body -- which statements to repeat
    2. Loop test condition -- when to loop and when to stop
    3. Loop test update -- must change something to exit the loop
    4. Initialization code -- how to get started correctly
  • The for loop lets us specify the last three items inside the for statement
  • In addition we looked at the off-by-one error
  • The off-by-one error occurs when we make a logic error about a boundary condition like the start or end value of a loop

Check Yourself

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. What must you always consider when designing a looping algorithm? (5.1.1)
  2. What makes a loop a counting loop? (5.1.2)
  3. What does the following code display: (5.1.2)
    for (int counter = 0; counter < 0; counter++) {
        cout << counter << endl;
    }
    
  4. What does the following code display: (5.1.2)
    for (int counter = 5; counter > 0; counter--) {
        cout << counter << endl;
    }
    
  5. How do you code a loop to sum numbers? (5.1.3)
  6. What is a "fence-post error"? (5.1.5)

5.4: Midterm Preparation

Learner Outcomes

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

  • Discuss how to prepare for the midterm exam
  • Describe how to take the midterm exam

5.4.1: About the Exam

  • The exam covers material from the first four lessons and including while-loops
  • Exam question types include multiple choice and short programming problems
  • You will have about 45 minutes to complete the exam
    Last Name Section Start Time
    A-L Day 2:30 PM
    L-Z Day 3:30 PM
    A-K Evening 8:00 PM
    L-Z Evening 9:00 PM
  • I am using Canvas to administer the test in the classroom
  • Since there are more students than computers, we must take the exams in shifts
  • Shifts are determined by your last name and section as shown above
  • If you want to change shifts then make arrangements to switch with another student who is on the other shift and email the instructor the information

Ground Rules

  • You must attend the exam or you will receive a score of zero (0)
    • Except by prior arrangement with the instructor
  • You must bring a valid ID to the exam
  • The exam is closed books and closed notes
    • However, you may have one 3" x 5" card of handwritten notes for the exam
  • Blank scratch paper is allowed.
  • You must use a classroom computer to take the exam in Canvas
  • No applications can be run on the computer except the browser.
    • Thus, you may NOT use the computer to compile or run programs
  • The browser can only show the exam window--all other windows must be closed.
    • You may NOT use the computer to view documents on the Internet
    • Once you start the exam, do not click to other parts of the computer
  • No electronic devices like cell phones, calculators or music players.
    • If you have a cell phone visible or in use during the exam, you will automatically fail
  • No communication with anyone but the instructor during the exam.

3"x5" Card Requirements

  • Put your name on your card
  • Maximum card (or paper) size is 3 inches by 5 inches
  • You may use both sides of the card
  • Notes must be handwritten and NOT photocopied
  • No more than three statements in a sequence on the card — only snippets
  • Any 3" x 5" cards violating these rules will be confiscated before the test
  • You must turn in your 3" x 5" card after the exam in any case

5.4.2: Test Preparation Self Assessment (3m)

Follow this link and answer the Test Preparation Self Assessment questions.

Discussions Questions

  • How are these practices beneficial?
  • What are your successful strategies for exam preparation?
  • How much time do you dedicate to test preparation?

5.4.3: How to Study for the Exam

forked road
  • No one can ace the test without understanding the material and the key to understanding is to study
  • To get the best grade you need to thoroughly prepare for the test well in advance
  • With the midterm approaching, you have a choice:
    • Study and do well, or
    • Not study and do less than your best
  • Victims are people who let their lives control them, like a pawn on a chessboard
  • Creators are people who controls their own life, like a person playing chess
  • You can take responsibility for studying and do well on a test
  • Or you can make excuses and do less than you are capable of on a test

Boosting Your Performance

Here are some steps you can take to improve your test results:

  1. Compile a list of topics you might be tested on.

    Look over your assignments, exercises, and lecture notes to determine what you covered. Write a list of topics from these sources.

  2. Make sure you understand all the topics on your list.

    Correct any mistakes you may have made in your assignments or exercises.

  3. Identify the most probable exam topics for thorough study.

    To do well, you need deep understanding of the test topics. Oftentimes, you can tell what is on a test simply by which topics the instructor spends the most time talking about.

  4. Create a list of test questions.

    Turn headings from the textbook and lecture notes into questions. Look at the section summaries in the lectures and read the Check Yourself questions.

  5. Study your questions over and over until you know them perfectly.

    Make flash cards with questions on one side and answers on the other. Carry the cards with you and review them when you have a few minutes available. Have other people ask you questions from your flash cards.

  6. Prepare your 3"x5" card of test notes.

    Since the instructor allows a 3"x5" card, make use of it. For the topics you had the most trouble with, write down a short note or summary. If the pressure of the test causes you to forget something, you can refer to your card.

More Information

Exercise 5.4: Preparing Exam Questions (3m)

Take three minutes to review and choose one of the following topics for A5-Midterm 1 Preparation. Post the questions in the Discussions area of Canvas titled "Midterm 1 Study Questions" for XP.

There cannot be more than two posts per topic and all the questions for a post must be unique. Thus if two people select the same topic, the second person who posts on the topic must have different questions than the first person.

Exam Topics

  1. Compiling, errors and debugging: (1.3.5, 2.1.1, 2.4)
  2. Variable declaration: (2.2.2, 3.1)
  3. Variable assignment flow: (3.1.4, Exercise 3.1)
  4. User I/O: (2.2.3, 3.2.4)
  5. Arithmetic: (2.3.1-3, 4.1.1)
  6. Integer division and modulus: (2.3.4)
  7. Math functions: (2.3.5)
  8. Type char and ASCII: (3.2.1)
  9. Type string: (3.2.2-3)
  10. String concatenation: (3.2.5)
  11. String functions: (3.2.6)
  12. if-statements: (3.3.1)
  13. if-else statements: (3.3.4)
  14. Relational operators: (3.3.2-3)
  15. Pair programming: (3.4)
  16. Exponential notation: (4.1.2)
  17. Decimal formatting: (4.1.3)
  18. Constants and magic numbers: (4.1.4)
  19. Assignment operators: (4.1.5)
  20. Type casting: (4.1.6)
  21. Integer range and overflow: (4.1.7)
  22. Numeric precision: (4.1.7)
  23. Multiple alternatives: (4.2.2-3)
  24. Nested branches: (4.2.4)
  25. Boolean variables : (4.2.5)
  26. Boolean (logical) operators: (4.2.6)
  27. Loops and while statements: (4.3, 5.3)

5.4.4: More Test Preparation

  • To help you study, you can use this review game: Greenfoot Jeopardy
  • Must view in Firefox or Internet Explorer (not Edge or Chrome)
  • Also requires Java installation, so may want to use computers at school
  • Do NOT update Java before playing Greenfoot Jeopardy
  • Press the Run button
  • Start the game with the "cpp.txt" file

Practice Exam

  • To help your understanding of how the midterm will operate, I am providing a practice exam in Canvas
  • The practice exam is for you to practice with on your own and will not be graded
  • The questions are intended to help you get a "feel" for taking an exam in Canvas
  • The questions are NOT intended to tell you everything that is on the exam
  • Suggestion: prepare first and then try the practice exam
  • This will give you a better understanding of how much more preparation you need
  • Things to Know Before Taking a Quiz/Exam in Canvas

Exam Taking Tips

  • If you get stuck on a question, make your best guess and return later
  • If you are equally uncertain between two choices, go with your first impression
  • When writing code, do NOT add more than the problem asks for
  • You do not need to comment code for tests and exams
    • Unless specifically instructed to in the exam question
  • Use the full time available
    • Check your work if you finish early
  • Any questions?

Wrap Up

Due Next:
A4-Making Selections (9/28/17)
A5-Midterm 1 Preparation (10/5/17)
  • When class is over, please shut down your computer
  • You may complete unfinished exercises at the end of the class or at any time before the next class.
Last Updated: October 04 2017 @22:32:18