7: Loops 2 and Vectors

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?

7.1: Cooperative Quizzes

Quiz Part 1: Individual Readiness Assessment

Quiz Part 2: Team Readiness Assessment (15m)

Quiz Appeals

7.2: Do while Loops

Reviewing do-while loops

Image
Image source

Do-while loop example

#include <iostream>
using namespace std;

int main() {
    double input = 0.0; // initialize value
    do {
        cout << "Enter a positive number: ";
        cin >> input;
        if (input <= 0.0) {
            cout << "You must enter a positive number\n";
        }
    } while (input <= 0.0); // test condition at end
    cout << "You entered: " << input << endl;

    return 0;
}

CA 7.2: Coding Challenge Questions

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

If so, list the CA numbers in Chat

Exercise 7.2: Processing User Input (10m)

In this exercise we use indefinite loops to process user input and to ensure correct 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 Repl.it 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 sumScores to 0
    set nextScore to 0
    set count to 0
    

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

  3. Now we want to 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:

    Listing of while loop

  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:

    Score 1: 38
    Score 2: 39
    Score 3: -1
    
    Sum of scores: 77
    
  6. We could write our indefinite loop using a do-while loop instead. Replace your current loop with the following:

    Listing of do-while loop

    Note that the statements inside the loop did not change, only the loop statement itself. To make sure you made the changes correctly, compile and run your code and check to see if it works the same. The difference between a while and do-while loop is that a do-while ensures the body of the loop is executed at least once.

  7. 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.

7.3: Declaring and Accessing Vectors

Reviewing Vector Declarations and Access

Accessing Vector Elements

Vector Size

CA 7.3: Coding Challenge Questions

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

If so, list the CA numbers in Chat

Exercise 7.3: Vector Basics (12m)

In this exercise we create a vector.

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. Inside main(), add a statement to define a vector of type double named temp along with a list of five (5) randomly chosen values.
  3. Compile your code to make sure it has correct syntax.
  4. Print element 0 like:
    cout << temp.at(0) << endl;
    
  5. Compile your code to make sure it has correct syntax. Run the code and verify you see the first value of your vector.
  6. Add a for-loop that accesses every index of the temp vector and prints every value to the screen like:
    for (unsigned i = 0; i < temp.size(); ++i) {
        cout << temp.at(i) << endl;
    }
    
  7. Compile your code to make sure it has correct syntax. Run the code and verify you see the all the value of your vector.
  8. Declare a summing variable named total before the loop and initialize the variable to zero (0).
  9. Inside the loop, add the indexed temp.at(i) value to total every time the loop iterates.
    for (unsigned i = 0; i < temp.size(); i++) {
        cout << temp.at(i) << endl;
        total = total + temp.at(i);
    }
    
  10. After the loop completes, print the value of total.
  11. Compile your code to make sure it has correct syntax. Run the code and verify you see a correct value for total.
  12. Once satisfied with your code, copy your code into a text editor, save the file as "templist.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.

7.4: Iterating Vectors

Reviewing Vector Iteration

CA 7.4: Coding Challenge Questions

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

If so, list the CA numbers in Chat

Exercise 7.4: Iterating Vectors (10m)

In this exercise we use iteration for common computations on a vector.

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>
    #include <vector>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. Inside main(), add a statement to define a vector of type double named temp along with a list of five (5) randomly chosen values.
  3. Next, declare variables of type double to store the sum, minimum and maximum values of the vector, like:
    double sum = 0;
    double min = temp.at(0);
    double max = temp.at(0);
    

    Notice we initialize the sum to 0 and the min and max to the first value of the vector. Add a comment after each variable declaration to explain why it is initialized in that way.

  4. Add a for-loop that accesses every index of the temp vector and adds it to the sum, like:
    for (unsigned i = 0; i < temp.size(); ++i) {
        sum = sum + temp.at(i);
    }
    
  5. After the for loop, print the sum, average, minimum and maximum values like:
    cout << "Sum=" << sum << endl;
    cout << "Average=" << sum / temp.size() << endl;
    cout << "Minimum=" << min << endl;
    cout << "Maximum=" << max << endl;
    
  6. Inside the for loop, after the sum computation, add an if statement to test for a minimum value, like:
    if (min > temp.at(i)) {
        min = temp.at(i);
    }
    
  7. Similarly, add an if statement to test for a maximum value.
  8. Compile your code to make sure it has correct syntax. Run the code and verify you see a correct value for sum, average, minimum and maximum.
  9. Once satisfied with your code, copy your code into a text editor, save the file as "iterate.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.

7.5: Multiple Vectors

Reviewing Multiple Vectors

A Slice in Multiple Vectors

Two Vectors Storing Related Data
Name Vector
 
 
 
 
Bread
 
 
 
 
 
Price Vector 
 .at(0)
 .at(1)
 .at(2)
 .at(3)
2.99.at(4) Slice
 .at(5)
 .at(6)
 .at(7)
 .at(8)
 .at(9)

Accessing Data in Multple Vectors

Example of Multiple Vectors

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<string> product = { "Apple", "Bread", "Cheese", "Milk", "Orange" };
    vector<double> price = { 1.62, 2.99, 4.95, 3.95, 1.10 };
    cout << "Enter a product name: ";
    string name;
    cin >> name;
    for (unsigned i = 0; i < product.size(); i++) {
        if (product.at(i) == name) {
            cout << name << " costs " << price.at(i) << endl;
        }
    }

    return 0;
}

CA 7.5: Coding Challenge Questions

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

If so, list the CA numbers in Chat

Exercise 7.5: Iterating Multiple Vectors (10m)

In this exercise we explore the use of multiple vectors.

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() {
        // add code here
    
        return 0;
    }
    
  2. Next we add two vectors to the program with parallel data
    vector<string> area = { "Aptos", "Capitola", "Felton",
        "Santa Cruz", "Watsonville" };
    vector<int> particleCounts = { 37, 39, 51, 53, 42 };
    
  3. Now add statements to let the user input a location. Notice that locations may have spaces in names so we must use getline().
  4. Now we want to add a for loop to look up the location in the area vector. Inside the for loop we place an if statement to test for a match between a vector element for area and the location entered by the user.
  5. When the program finds a match between the location and the area, we print the particle readings for the area.
    cout << location << " particle readings are "
         << particleCounts.at(i) << endl;
    
  6. Compile and run your code to make sure you completed the program correctly. When you run the program, the output should look like:
    Enter a location: Aptos
    Aptos particle readings are 37
    
  7. Once satisfied with your code, copy your code into a text editor, save the file as "particulates.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.

7.6: Vector push_back()

Reviewing Vector push_back()

Collecting and Displaying a Variable Number of Data Items

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> scores;

    cout << "Enter scores (-1 to quit):\n";
    int value = 0;
    while (value != -1) {
        cin >> value;
        if (value != -1) {
            scores.push_back(value);
        }
    }

    cout << "You entered:\n";
    for (unsigned i = 0; i < scores.size(); i++) {
        cout << scores.at(i) << endl;
    }

    return 0;
}

CA 7.6: Coding Challenge Questions

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

If so, list the CA numbers in Chat

Exercise 7.6: Adding Elements with push_back() (12m)

In this exercise we add and remove elements from the end of a vector.

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>
    #include <vector>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. Inside main(), add a statement to define a vector of type double named temp along with a list of five (5) randomly chosen values.
  3. Compile your code to make sure it has correct syntax.
  4. Add a for-loop that accesses every index of the temp vector and prints every value to the screen followed by a space. When run, the output should look like the following, depending on the numbers chosen.
    12.3 23.4 34.5 45.6 56.7
    
  5. Add two more elements to the temp vector using the push_back() function. For example, here is how to add one element:
    temp.push_back(42.1);
    
  6. Next add statements to print the vector size and the last element, like:
    cout << temp.size() << endl;
    cout << temp.back() << endl;
    
  7. Afer this, add another copy of the for-loop from step 4. When run, the output should look like the following, depending on the numbers chosen.
    12.3 23.4 34.5 45.6 56.7
    7
    24.6
    12.3 23.4 34.5 45.6 56.7 42.1 24.6
    
  8. Now remove the last element using pop_back() and then print the size and last element again:
    temp.pop_back();
    cout << temp.size() << endl;
    cout << temp.back() << endl;
    
  9. Afer this, add yet another copy of the for-loop from step 4. When run, the output should look like the following, depending on the numbers chosen.
    12.3 23.4 34.5 45.6 56.7
    7
    24.6
    12.3 23.4 34.5 45.6 56.7 42.1 24.6
    6
    42.1
    12.3 23.4 34.5 45.6 56.7 42.1
    
  10. Once satisfied with your code, copy your code into a text editor, save the file as "pushback.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.