# 7: Loops 2 and Vectors

## General Information

### Housekeeping

• 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 for review:

## 7.1: Cooperative Quizzes

• Quizzes assess the reading and participation activities due before the class meeting

### Quiz Part 1: Individual Readiness Assessment

• Must take this quiz before the class meeting 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 (15m)

• Must attend the class meeting to take this quiz
• Will move to breakout rooms with your team
• 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

### Quiz Appeals

• After completing the group quiz, group 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. Teams 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

## 7.2: Do while Loops

### Reviewing `do-while` loops

• 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
• One common use of a `do-while` loop is to validate user input
• The following code shows an example where we force the user to enter a positive value

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

If so, list the CA numbers in Chat

• 7.2.1: Basic do-while loop with user input.
• 7.2.2: 7.2.2: Do-while loop to prompt user input.

### 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() {

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:

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:

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

• Often times we need to process a list of data
• Vectors offer a convenient way to process such a list
• The vector data type is defined in the standard library `vector`:
```#include <vector>
using namespace std;
```
• As an example, the following is the definition of a vector named `scores` that holds 10 values of type `int`:
`vector<int> scores(10);`
• This code creates 10 contiguous elements in memory that each hold an `int`

• Another way to declare a vector is with a list of values to store
```vector<int> scores = { 90, 95, 97, 89, 98 }; // 5 values
```
• The above creates a vector with 5 elements

#### Accessing Vector Elements

• Once we have a vector, we specify which element to use with the `at()` function:
`scores.at(4) = 98;`
• The number inside the brackets is called an index
• Any element is a variable of the vector data type (`int` in this case) and can be used like a variable:
`cout << scores.at(4) << endl;`
• The index of a vector can be any integer value, which means we can use variables or expressions to specify the index
• This lets us use the counter variable of a loop as the vector index, like:
```for (int i = 0; i < 5; i++) {
cout << scores.at(i) << endl;
}
```

#### Vector Size

• We can find the size of a vector by calling the `size()` function
```vector<int> scores = { 90, 95, 97, 89, 98 };
cout << scores.size() << endl;
```
• The `size()` function is useful in counting loops:
```unsigned i;
for (i = 0; i < scores.size(); i++) {
// do something with scores[i]
cout << scores.at(i) << endl;
}
```
• The `unsigned` data type is shorthand for `unsigned int`

### CA 7.3: Coding Challenge Questions

If so, list the CA numbers in Chat

• 7.4.1: Enter the output for the vector.
• 7.4.2: Printing vector elements.
• 7.4.3: Printing vector elements with a for loop.

### 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() {

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

• Iterate means to make repeated use of a computational procedure, applying it each time to the result of the previous application
• Many uses of vectors involve iteration such as
• Finding a particular value
• Finding a minimum or maximum value
• Summing or averaging values
• To find some quantity in a vector, we iterate through the vector with a `for` loop
• For some iteration computation, like summing or averaging, we update a variable each time through the loop
```vector<int> scores = { 90, 95, 97, 89, 98 };
int sum = 0;
for (unsigned i = 0; i < scores.size(); i++) {
sum = sum + scores.at(i);
}
cout << "Sum=" << sum << endl;
cout << "Average=" << sum / scores.size() << endl;
```
• Other iterative computations require one or more `if` statements to test for a condition
```vector<int> scores = { 90, 95, 97, 89, 98 };
int value;
for (unsigned i = 0; i < scores.size(); i++) {
if (test condition) {
value = scores.at(i);
}
}
cout << value << endl;
```
• Then inside the `if` statement the code updates the value

### CA 7.4: Coding Challenge Questions

If so, list the CA numbers in Chat

• 7.6.1: Enter the output for the vector.
• 7.6.2: Finding values in vectors.
• 7.6.3: Populating a vector with a for loop.
• 7.6.4: Vector iteration: Sum of excess.
• 7.6.5: Printing vector elements separated by commas.

### 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() {

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

• Suppose we want to process a series of product data like name, price, quantity, etc.
• Here is some sample data:
Name Price
Milk 3.95
Cheese 3.95
• We want to be able to display the data and process the items in various ways
• One possibility is to create multiple vectors as shown in the diagram below
• Each slice (name, price, etc.) contains data that must be processed together and kept in order together

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

• To access data in multiple vectors, we search one vector for a desired values
• To search each element we use a for-loop
• Inside the for-loop we put an if-statement to selected the desired value
• After finding the desired value we use the index to access the other elements in the slice
• The following is a simple example of multiple 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

If so, list the CA numbers in Chat

• 7.7.1: Printing the sum of two vector elements.
• 7.7.2: Multiple vectors: Key and value.

### 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() {

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
```
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 here 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()`

• Defining a vector without an initial size creates an empty vector with no space for elements:
```vector<int> scores;
cout << scores.size() << endl;
```
• A vector of size 0 is actually useful because we can change the size of a vector
• If we know the size of data we are working with, then we should declare the size when we define the vector
• However, we do not always know the size of data we will work with
• Oftentimes the user will decide how many data items to enter into the program
• In this case, we can start with an empty vector and grow the vector whenever we add another element
• The `push_back()` function resizes the vector by adding one element to its end:
```scores.push_back(42);
cout << scores.size() << endl;
```
• Another member function, `back()`, returns the last value in a vector
```cout << scores.back() << endl;
```
• Yet another function, `pop_back()`, removes the last element of a vector, shrinking its size by one:
```scores.pop_back();
cout << scores.size() << endl;
```
• The example program listed below shows how to collect data with a variable number of elements

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

If so, list the CA numbers in Chat

• 7.9.1: Appending a new element to a vector.
• 7.9.2: Removing an element from the end of a vector.
• 7.9.3: Reading the vector's last element.

### 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() {

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 << "size: " << temp.size() << endl;
cout << "last: " << 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
size: 7
last: 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
size: 7
last: 24.6
12.3 23.4 34.5 45.6 56.7 42.1 24.6
size: 6
last: 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 here 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.