6. Loops continued

Review Topics


General Information

Housekeeping

  • Make sure you follow along with this page linked in Canvas
  • Please keep your microphone off unless you are asking a question
  • Please turn on camera if you can (optional)
  • Use chat if you would like to comment or ask questions

Announcements

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

  • Complete vacinations required to visit campus or sign up for future terms (instructions)
  • Remember that PAs and the Individual Readiness Assurance Quiz are due before class on Tuesday.
  • Remember to post in the Pair programming partners discussion group if you need a partner
  • Remember that CAs, Labs, and Class Exercises may be completed up to two days late but with a 10%/day penalty.
  • Remember that some lab solutions are posted in Canvas Modules
  • Food & Housing Resources: free food, meals, temporary and permanent housing
  • COVID-19 Resources and Information: Includes loaner-laptop information
  • Campus WiFi Access
  • Extra credit bonus points for the first student to report a problem

Homework Help

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

  • Those who fully did their homework and completed the midterm study preparations did better on the midterm than those who did not
  • For topics you found difficult, review the notes and homework, get help understanding, -- and then practice until perfect!
  • If you believe a question was graded incorrectly, please email me an explanation
  • We will have another midterm before the final
  • Grading policies are listed in the syllabus

6.1.2: Post Exam Survey

  • Please complete the following survey to help future students and the instructor. (5m)
  • Post Exam Survey

6.1.3: Making the Grade

  • Oftentimes students who get less than an "A" on the midterm wonder if they can still get an "A" in the course
  • Since this is the first midterm, the answer is "Yes" unless:
    • You have not completed most of the homework
    • AND you failed the midterm with < 50%
  • Even with the above, you can still pass the course and even get a "B"
  • However, you will need to start doing your homework fully and study more for the tests

Suggestions for Improving your Grade

  • Start planning and studying for the next midterm exam now
  • Take notes and update or rewrite them the day after a class meeting
  • Review your notes every week and identify possible exam problems
  • Analyze your homework and get help on items with which you have problems
  • Study with others by reviewing homework problems and practicing with possible exam questions
  • Use your instructors' student hours or SI to ask questions about material you don't understand

Exercise 6.1: Exam 1 Self-Reflection

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

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

  • Brain research shows that we can grow our brain interconnections
  • Like a muscle, the more we work with our brain the more it grows
  • When things are easy our brain may grow a little
  • However, the most growth occurs when we struggle with things
  • Research shows that our brain grows the most when we get a question wrong
  • So if we did not do well on the midterm, we have an opportunity to grow our brain
  • When we review and understand why we got something wrong, that is when our brain grows the most
  • If we keep improving when we get something wrong, we are on our way to a more capable brain

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: Readiness Assessment Quizzes

  • Reading and participation activities are due before the first class meeting of the week
  • Quizzes assess the comprehension of the reading and participation activities

Quiz Part 1: Individual Readiness Assessment

  • Complete this quiz solo to assess your reading comprehension and readiness
  • Must take this quiz before the first class meeting of the week to ensure you are ready for the team quiz
  • Quiz is open book and notes but timed
  • Highest score is counted so take the quiz multiple times

Quiz Part 2: Team Readiness Assessment (20m)

  • Must attend the class meeting to take this quiz
  • Login to Canvas
  • Will move to breakout rooms with your team
  • Make sure you have the access code for the exam
  • Openly discuss what you believe to be the best answers for the questions
  • Decide how to agree on the answers
    • Strive to reach a consensus on quiz answers
    • If no consensus, work it out as you and others in your group see fit
  • Turn in the quiz as a group
  • Each group member will receive the same score
  • Return to the main meeting room when finished

Quiz Appeals

  • After completing the team quiz, team members may appeal an answer
  • Appeals can be based on two criteria:
    1. Question is factually wrong

      Appeal must included citations to sources of information that document or support an alternative answer. Team may access reference materials during the appeal.

    2. Question is confusing based on it's wording

      Appeal must include an appropriate rewrite of questions or answers that you interpret as ambiguous or confusing.

  • Work with teammates to develop and write any appeals
  • Team has up to 24 hours after the quiz to email appeal to instructor
  • If appeal is granted, only the teams that submitted appeal gets credit

6.3: For Loops

A loop commonly must iterate a specific number of times, such as 10 times. We can use a while loop, but the situation is so common that a special kind of loop exists

.

A series of steps

6.3.1: Reviewing for statements

  • Counting is a very common way to use loops
  • Counting loops are controlled by a counter variable and are called counter-controlled loops
  • Visualize a counter-controlled loop as a series of steps to reach a goal
  • Each step is one iteration (repetition) of the loop
  • 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
    • i++: the update statement
  • Because counting loops are so common, C++ has a special statement:
    for (i = start; i < end; i++) {
       ...
    }
    
  • Notice the similarities and differences between the while and for statements
  • Following program contains a counting loop

Counter-Controlled-Loop Example

#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;
   cout << "for loop:\n";
   for (int i = 0; i < max; i++)
   {
      cout << i + 1 << endl;
   }

   return 0;
}
  • Note how the repeated code is indented inside the loop
  • This lets us see easily which code is repeated and which is not
  • Following are diagrams of the for-loop operation

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

Exercise 6.3a: 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 Replit 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.

6.3.2: Counting down

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:

  • What value should we use for start?
  • What expression should we use for the test condition?
  • What statement should we use for the update?

Exercise 6.3b: Counting Down (10m)

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

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 Replit 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.4: Loops and Strings

A common programming task is to iterate through a string, examining each character.

6.4.1: Reviewing loops and strings

  • A string is a series of characters enclosed in double quotes
  • We store text in a variable of type string, like:
    string s1 = "Hello Mom!";
  • A character is a single letter, number or special symbol
  • We store a a single character using a variable of type char, such as:
    char letterA = 'A';
    char letterB = 'B';
    
  • Each character is stored as a number, using its ASCII code
  • Strings are stored in a character sequence starting at 0 (zero)

    String character position

  • We access individual characters of a string using the at() function
  • Strings are a special type of variable, called objects, that have functions associated with them
  • We iterate through a string using a loop and the size() member function:
    string s = "abcdef";
    for (unsigned i = 0; i < s.size(); i++) {
        cout << "Char " << i << ": " << s.at(i) << endl;
    }
    

Exercise 6.4: Iterating Strings (12m)

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 Replit 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.5: Nested Loops

A nested loop is a loop that appears in the body of another loop.

6.5.1: Reviewing Nested Loops

  • Some looping applications have loops nested within other loops
  • The structure of nested loops looks like:
    for (int outer = 1; outer < 4; outer++)
    {
        for (int inner = 1; inner < 4; inner++)
        {
            cout << outer << " " << inner << endl;
        }
    }
    
  • By analogy, nested loops are like an odometer on a car
  • The inner loop is like the digit to the right on an odometer
  • The numbers to the right loop completely before the number to the left increments by one

    odometer

  • When analyzing or designing nested loops, we start with the inner loop
  • After we know what the inner loop should do, we work on the outer loop

6.5.2: Code Indentation and Automatic Formatting

  • When code has many braces it is easy to get lost
  • The solution is correct indentation
  • Closing braces need to match up with opening braces or statements
  • If you have problems with indentations then try using a program to correctly align braces
  • One program is: Code Beautify C++ Formatter
  • To use:
    1. Paste code into the box
    2. Select 3 indent
    3. Press Format
    4. Copy the formatted code to your text editor

Example of Poorly Formatted Code

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

int main() {
cout << "Outer\tInner\n";
    for (int outer = 1; outer < 4; outer++)
{
for (int inner = 1; inner < 4; inner++) {
cout << outer << "\t" << inner << endl; }
cout << "\t(End of inner loop)\n"; }
cout << "(End of outer loop)\n";
}

Check Yourself

For the unformatted code above:

  1. The opening brace of the inner loop is line ________.
  2. The closing brace of the inner loop is line ________.
  3. The opening brace of the outer loop is line ________.
  4. The closing brace of the outer loop is line ________.

Exercise 6.5: 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 Replit 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. Style your code before copying:
    • If using Replit enter the following into the terminal window:
      clang-format -style="Google" main.cpp
      
    • Otherwise use the Code Beautify C++ Formatter code formatter
  12. Once satisfied with your code, copy your formatted 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.

6.6: More about while loops

The while loop is used to repeat blocks of code indefinitely.

6.6.1: Indefinite Loops

  • Recall our looping application that simulated the play of an exciting game
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main() {
    char repeat = 'y';
    while ('y' == repeat) {
        cout << "\nPlaying an exciting game!\n";
        cout << "Do you want to play again? (y/n) ";
        cin >> repeat;
    }
    cout << "\nThanks for playing!\n";

    return 0;
}
  • Loops of this type are called indefinite loops because we do not know in advance how many time the loop will execute
  • Instead, the loop executes until some condition is satisfied
  • This behavior is different from a counting loop where we know how many times the loop will execute before the loop starts
  • Most problems solved with indefinite loops make use of while statements

While loop flow chart

Check Yourself

  1. True or false: with an indefinite loop, you often know in advance how many times the loop will repeat.
  2. True or false: the best looping statement for an indefinite loop is a for statement.
  3. True or false: a counting loop is a good example of an indefinite loop.

6.6.2: Indefinite Loop Example

  • As another example of an indefinite loop, let us look at the problem of compounding interest
  • If we invest $10,000 at 5% interest, compounded annually, our savings grow like this:
    Year Balance
    0 $10,000
    1 $10,500
    2 $11,025
    3 $11,576.25
    4 $12,155.06
    5 $12,762.82
  • How many years does it take for the initial investment to double?
  • To solve this problem we can use a while loop:
    double balance = 10000;
    int year = 0;
    while (balance < 20000) {
        year++;
        double interest = balance * 0.05; // 5% interest
        balance = balance + interest;
    }
    
  • We can make the loop work for any interest rate, starting balance and target amount as shown below

Program with an Indefinite Loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double balance = 0;
    double target = 0;
    double rate = 0;

    cout << "Enter the starting balance: ";
    cin >> balance;
    cout << "Enter the interest rate as a percent: ";
    cin >> rate;
    cout << "Enter the target amount: ";
    cin >> target;

    cout << fixed << setprecision(2);
    cout << "\nYear\tBalance\n";

    int year = 0;
    cout << year << '\t' << balance << endl;
    while (balance < target) {
        year++;
        double interest = balance * rate / 100;
        balance = balance + interest;
        cout << year << '\t' << balance << endl;
    }
    cout << "\nTarget amount of $" << target
         << " reached after " << year << " years.\n" ;

    return 0;
}

Try It: Indefinite Loops

Run the above program (Replit) and find the answers the following questions. Post your answers in chat.

  1. The above program includes the <iomanip> library because of ________.
  2. If the interest rate is 5%, the number of years before an investment doubles is ________.
  3. The number of years for an investment of $10,000 to triple at 5% interest is ________ .
  4. If the interest rate is 1%, the number of years for an investment of $10,000 to double is ________.
  5. Can you easily predict how times the loop in the above program would repeat to double an investments at a certain interest rate? If so, how?

6.6.3: Processing a Sequence of Inputs

  • Another common use for indefinite loops is to process a sequence of inputs
  • As an example, let us add up (sum) a series of numbers
  • Every number input is added to the sum
  • We use a loop to repeat the input until the user decides to stop
  • Since we do not know how many number the user will enter, we use an indefinite loop as shown below
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

int main() {
    double input = 0;
    double sum = 0;
    char repeat = 'y';

    cout << "I will add up numbers for you\n\n";
    while ('y' == repeat) {
        cout << "So far, sum = " << sum << endl;
        cout << "Enter a number: ";
        cin >> input;
        sum = sum + input;

        cout << "Another number? (y/n) ";
        cin >> repeat;
    }
    cout << "Ending sum: " << sum << endl;

    return 0;
}

Terminating the Input with a Sentinel

A sentry

  • Whenever we read a sequence of input values, we need to have some way of terminating the input loop
  • We could use a separate variable and input statement as we have done before:
    char repeat = 'y';
    while ('y' == repeat) {
        // ... statements to repeat
        cin >> repeat;
    }
    
  • However, when entering numbers (or other data) repeatedly, answering an extra question each time through the loop becomes annoying
  • One way to avoid asking an extra question is to use a sentinel value
  • A sentinel is guard who watches for something to happen
  • Similarly, a sentinel in a program watches for a specific sentinel value that signals termination of a loop
  • To use a sentinel value, we must have a special value in the input
  • Some commonly used sentinel values for numeric input are 0 or -1
  • However, if our application suggests another value, then we should use that value
  • In psuedocode, a sentinel loop generally looks like this:
    read the first value
    while value is not the sentinel
        process the value
        read the next value
    
  • The following program is an update of the previous program to use a sentinel value to end the loop

Example Application Using a Sentinel Value for the Loop Test

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

int main() {
    double input = 0;
    double sum = 0;

    cout << "I will add up numbers for you\n\n";
    cout << "Enter a number or 0 to exit: ";
    cin >> input;
    while (input != 0) {
        sum = sum + input;
        cout << "So far, sum = " << sum << endl;
        cout << "Enter a number or 0 to exit: ";
        cin >> input;
    }
    cout << "Ending sum: " << sum << endl;

    return 0;
}

Check Yourself

  1. A special value a program looks for in the input stream to know when to end user input is called a(n) ________ value.
  2. In the example application, if a user enters a 0 as their first input the loop ________.
  3. True or false: it is always possible to have a sentinel value. If you think it is not possible, give an example.

6.6.4: Maximum and Minimum Values

  • Sometimes we need to find the maximum or minimum number of a group
  • For instance we may want to know the highest score on a test
  • We further explore the algorithm in the following activity

Diagram of Finding a Maximum Value

Finding a maximum value
source

Translating to C++

  • We use a loop to ask the user for a new value repeatedly
  • Unless we know the number of values in advance we use an indefinite loop
  • To store a maximum (or minimum) value we use a variable
  • Remember that in C++ declaring a variable does not assign it a value
    int max; // the value of the variable is undefined
    
  • Thus we need to assign an initial value to the variable
  • Assigning a value of 0 is often a bad choice
    int max = 0; // NO!!
    
  • Instead we need to initialize with a possible value
    int max = firstValue; // Yes!!
    
  • As we get each new value, we test to see if it is larger than the previous maximum
    if (nextValue > max) {
        max = nextValue;
    }
    
  • If it is larger, we assign the value to be the new maximum
  • Finding a minimum value is similar but the test condition changes

Check Yourself

  1. Unless we know the number of values in advance, we repeatedly collect input inside a(n) ________ loop.
    1. counting
    2. for
    3. if
    4. indefinite
  2. To store a minimum or maximum value in a series of numbers we use a ________.
  3. To initialize a variable storing a minimum or maximum value we use the ________.
    1. number 0
    2. first value collected
    3. last value collected
    4. average value collected
  4. To compare if the next value is smaller or larger than the current value, we use a(n) ________ statement.

Exercise 6.6: Processing User Input (15m)

In this exercise we use indefinite loops to process user input and to find a maximum value.

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 Replit and copy the following code into the text editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. Declare two variables of type double named sumScores and nextScore and initialize the variables to 0. In addition, declare an integer variable named count and initialize it to 0. The following is the pseudocode for these steps:
    set nextScore to 0 // Why can nextScore be set to 0?
    set sumScores to 0 // Why should sumScores be set to 0?
    set count to 0 // Why should count be set to 0?
    

    Compile your code to make sure you declared the variables correctly.

  3. After declaring the variables, we use a loop to enter a series of scores. Since we do not know how many scores to enter, we use an indefinite loop like the following:
    while (nextScore >= 0) {
        count++;
        cout << "Enter score #" << count << ": ";
        cin >> nextScore;
        if (nextScore >= 0) {
            sumScores = sumScores + nextScore;
        }
    }
    
  4. In addition, add a statement to display sumScores after the loop.
    cout << "\nSum of scores: " << sumScores << endl;
    
  5. Compile and run your code to make sure you added the loop correctly. To exit the loop you will need to enter a negative number.

    When you run the program, the output should look like:

    Enter score #1: 38
    Enter score #2: 39
    Enter score #3: -1
    
    Sum of scores: 77
    
  6. Next add another if-statement to find a maximum value. Use the following psuedocode to guide your development:
    nextScore = next input
    largestValueSoFar = nextScore
    while there are more inputs
       nextScore = next input
       if nextScore > largestValueSoFar
          largestValueSoFar = nextScore
    
  7. Compile and run your code to make sure you updated the code correctly. When you run the program, the output should look like:
    Enter score #1: 38
    Enter score #2: 39
    Enter score #3: -1
    
    Sum of scores: 77
    Maximum score: 39
    
  8. Once satisfied with your code, copy it into a text editor, save the file as "scores.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.7: Do-while Loops

A do-while loop is a loop construct that first executes the loop body's statements, then checks the loop condition.

6.7.1: Reviewing do-while loops

Image
Image source

  • Sometimes we want to execute the body of a loop at least once and perform the loop test after the body was executed
  • For this we can use the do-while (or just do) loop:
    do {
       statements
    } while (test); // loop test
    
  • Where:
    • statements: the statements to execute the first time and repeatedly while the test remains true
    • test: the test condition to evaluate
  • The loop test is placed after the body and executes at the end of the loop
  • The statements in the body of the loop always execute at least once
  • The following code shows an example where we sum numbers

Example of do-while loop

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() {
    double input = 0;
    double sum = 0;

    cout << "I will add up numbers for you\n\n";
    do {
        cout << "Enter a number or 0 to exit: ";
        cin >> input;
        sum = sum + input;
        cout << "So far, sum = " << sum << endl;
    } while (input != 0); // test condition at end
    cout << "Ending sum: " << sum << endl;

    return 0;
}

Comparison to while Loop:

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

int main() {
    double input = 0;
    double sum = 0;

    cout << "I will add up numbers for you\n\n";
    cout << "Enter a number or 0 to exit: ";
    cin >> input;
    while (input != 0) {
        sum = sum + input;
        cout << "So far, sum = " << sum << endl;
        cout << "Enter a number or 0 to exit: ";
        cin >> input;
    }
    cout << "Ending sum: " << sum << endl;

    return 0;
}

Validating User Input

  1. One common use of a do-while loop is to validate user input
  2. We explore input validation in the following exercise

Exercise 6.7: Using the do-while loop (10m)

In this exercise we use do-while loops to validate user input.

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 Replit and copy the following program into a text editor.
      #include <iostream>
      using namespace std;
      
      int main() {
          double input = 0.0; // initialize value
          // Start your do-while loop here
          cout << "Enter a positive number: ";
          cin >> input;
          // Enter more code here
          cout << "You entered: " << input << endl;
          return 0;
      }
      
    2. The problem with the above code is the user may enter negative values. Add a do-while loop so the user must enter a positive value or 0 to continue.
      do {
          // Code to prompt for and enter a value
      } while (test condition);
      
    3. While the user may need a positive number to continue, we still need an error message to warn the user of their error. Add the following if-statement after the input statement.
      if (input <= 0.0) {
          cout << "You must enter a positive number\n";
      }
      
    4. Make sure you made the changes correctly by compiling and running your code.
    5. Once satisfied with your code, copy it into a text editor, save the file as "validate.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.

    Deliverables

    For this week's exercises we are turning in these files:

    Remember that when submitting multiple files to Canvas, you must submit all files in the same session. For instuction on submitting multiple files for an assignment see the Canvas guide on How do I upload a file as an assignment submission in Canvas? section: Submit Assignment.

    Last Updated: October 01 2021 @02:53:50