After completing the group quiz, group members may appeal an answer
Appeals can be based on two criteria:
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.
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
In this exercise we explore how call-by-reference parameters differ from call-by-value parameters.
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
Start Repl.it and copy the following code into the code editor.
#include <iostream>
using namespace std;
void swap(int var1, int var2);
int main() {
int num1 = 0, num2 = 0;
cout << "Enter two integers: ";
cin >> num1 >> num2;
swap(num1, num2);
cout << "After calling function: "
<< num1 << " " << num2 << endl;
return 0;
}
void swap(int var1, int var2) {
int temp = var1;
var1 = var2;
var2 = temp;
}
Compile and run your code to make sure you added the code correctly.
When you run the program, the output should look like:
Enter two integers: 1 2
After calling function: 1 2
Notice that num1 and num2 have the same values before and after calling the function swap(). Any value assigned to var1 and var2 has no effect on num1 and num2. For more information, see section: 8.3.1: Parameter Passing and Value Parameters.
Change your program by adding the four ampersands (&) circled below:
The ampersands tell C++ to use call-by-reference when passing parameter values.
Compile and run the modified program to make sure you made the changes correctly. When you run the program, the output should look like this:
Enter two integers: 1 2
After calling function: 2 1
Notice that num1 and num2 have different values before and after calling the function swap(). Any value assigned to var1 and var2 change num1 and num2 respectively. For more information, see section: 8.3.2: Using Reference Parameters.
Once satisfied with your code, copy it into a text editor, save the file as "swap.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.
We may write functions to work with vector parameters
By writing a function we gain the benefits of a modular design including:
Making main() easier to read and understand
Modular development to allow reuse of functions
Incremental development where the functions can be written and tested separately from the rest of the program
Avoiding redundant code
One such function is displaying the elements of a vector to the screen
The following example shows a print() function
Example Code
#include <iostream>
#include <vector>
using namespace std;
/**
Prints all the elements in a vector to the console.
@param data the vector to print.
*/
void print(vector<int> data) {
for (unsigned i = 0; i < data.size(); i++) {
cout << data.at(i) << " ";
}
cout << endl;
}
int main() {
const int SIZE = 20;
const int MAX_NUM = 100;
srand(time(0));
vector<int> test(SIZE);
for (unsigned i = 0; i < test.size(); i++) {
test.at(i) = 1 + rand() % MAX_NUM;
}
print(test);
return 0;
}
Linear Search
One useful function is to look for a particular value in a vector
An easy and straightforward approach is linear search (a.k.a. sequential search)
In linear search we:
Start at the beginning of the list
Compare each value in the list looking for matches:
If the value is found, then return the index where the element was found
If the loop reaches the end of the list, return "not found"
Linear search is easy to implement using a simple loop:
int find(const vector<int>& data, int item) {
for (unsigned i = 0; i < data.size(); i++) {
if (item == data.at(i)) {
return i;
}
}
return -1;
}
Removing an Element
Often, functions modify the vector contents such as removing an element from a list
If order does not matter then we can:
Overwrite the element to be removed with the last element of the vector
Shrink the size of the vector
However, if order matters then we must:
Move all elements, after the one to remove, up towards 0 by one slot
Shrink the size of the vector
Again, we implement this operation using a loop:
void erase(vector<int>& data, int pos) {
for (unsigned i = pos; i < data.size() - 1; i++) {
data.at(i) = data[i+1];
}
data.pop_back();
}
Inserting an Element
In addition to removing items from a list, we often need to insert elements
We can either add elements to the end of a list or in the middle
If we add items to the end, we may just call the push_back() function of the vector:
data.push_back(item);
However, if we want to insert an item in the middle of a list we must:
Add a new element at the end of the vector
Copy elements down towards the end by one index from the end of the list to the insertion index
Assign the new value at the insertion index
Again, we implement this operation using a loop:
void insert(vector<int>& data, int pos, int value) {
int last = data.size() - 1;
data.push_back(data.at(last));
for (int i = last; i > pos; i--) {
data.at(i) = data.at(i - 1);
}
data.at(pos) = value;
}
Exercise 9.3: Coding Functions with Vector Parameters (20m)
In this exercise we explore how to code vector algorithms.
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
Download the starter code and save it to a convenient location like the Desktop.
Notice the menu provided and how the menu is implemented in code with a loop and if-statements. When entering a 0, as shown in aqua italics above (for emphasis), the program should exit.
Add the following print() function to the starter code after main().
void print(vector<int> data) {
for (unsigned i = 0; i < data.size(); i++) {
cout << data.at(i) << " ";
}
cout << endl;
}
Uncomment the call to print() in the main() function and then compile and run your program to test the changes you made. When run you should see output like:
Notice the list of numbers printed, which are the numbers stored in the vector.
Add the find() function to the starter code:
int find(const vector<int>& data, int item) {
for (unsigned i = 0; i < data.size(); i++) {
if (item == data.at(i)) {
return i;
}
}
return -1;
}
Uncomment the call to find() in the main() function and then compile and run your program to test the changes you made. When run you should see output like:
Vector Algorithms
Vector data: 5 7 4 2 8 6 1 9 0 3
0. Exit program
1. Find item
2. Remove item
3. Insert new item
Choice (0-3): 1
Enter the number to find: 8
Found 8 at position 4.
Vector data: 5 7 4 2 8 6 1 9 0 3
0. Exit program
1. Find item
2. Remove item
3. Insert new item
Choice (0-3): 0
Goodbye!
Notice the position number (index) returned by the find() function.
Add the following erase() function which deletes an element while maintaining order.
void erase(vector<int>& data, int pos) {
for (unsigned i = pos; i < data.size() - 1; i++) {
data.at(i) = data[i+1];
}
data.pop_back();
}
Uncomment the call to erase() in the main() function and then compile and run your program to test the changes you made. When run you should see output like:
Notice the number for the position (index) is now gone. In our example, the number 4 is gone from position 2.
Add the following insert() function which inserts an element into the vector while maintaining order.
void insert(vector<int>& data, int pos, int value) {
int last = data.size() - 1;
data.push_back(data.at(last));
for (int i = last; i > pos; i--) {
data.at(i) = data.at(i - 1);
}
data.at(pos) = value;
}
Uncomment the call to insert() in the main() function and then compile and run your program to test the changes you made. When run you should see output like:
Vector Algorithms
Vector data: 5 7 4 2 8 6 1 9 0 3
0. Exit program
1. Find item
2. Remove item
3. Insert new item
Choice (0-3): 3
Value to insert: 42
Position to insert the value: 5
Vector data: 5 7 4 2 8 42 6 1 9 0 3
0. Exit program
1. Find item
2. Remove item
3. Insert new item
Choice (0-3): 0
Goodbye!
Notice the element for the position (index) is now gone.
Once satisfied with your code, copy your code into a text editor, save the file as "algorithms.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.
Example Completed Program
#include <iostream>
#include <vector>
using namespace std;
/**
Prints all the elements in a vector to the console.
@param v the vector to print
*/
void print(vector<int> v);
/**
Finds the position of an item in a vector.
@param v The vector with the elements to search.
@param item The value to search for.
@return The index of the first match, or -1 if not
found.
*/
int find(const vector<int>& v, int item);
/**
Removes an item from the vector preserving the order
and reducing the size of the vector by one.
@param v The vector with the element to remove.
@param pos The number of the element to remove.
*/
void erase(vector<int>& v, int pos);
/**
Inserts an item into a vector.
@param v The vector to which to add the element.
@param pos The index before which to insert the
element.
@param value The element to insert.
*/
void insert(vector<int>& v, int pos, int value);
int main() {
vector<int> list = { 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
int choice = 1;
cout << "Vector Algorithms\n";
while (choice != 0) {
cout << "\nVector data: ";
print(list);
cout << "\n0. Exit program\n"
<< "1. Find item\n"
<< "2. Remove item\n"
<< "3. Insert new item\n"
<< "Choice (0-3): ";
cin >> choice;
if (choice == 1) {
int index = -1;
int item = 0;
cout << "Enter the number to find: ";
cin >> item;
index = find(list, item);
cout << "Found " << item << " at position " << index << ".\n";
} else if (choice == 2) {
int pos = 0;
cout << "Position to remove value: ";
cin >> pos;
erase(list, pos);
} else if (choice == 3) {
int value = 0;
cout << "Value to insert: ";
cin >> value;
int pos = 0;
cout << "Position to insert the value: ";
cin >> pos;
insert(list, pos, value);
} else if (choice != 0) {
cout << "\nInvalid choice!\n";
}
}
cout << "\nGoodbye!\n";
return 0;
}
void print(vector<int> data) {
for (unsigned i = 0; i < data.size(); i++) {
cout << data.at(i) << " ";
}
cout << endl;
}
int find(const vector<int>& data, int item) {
for (unsigned i = 0; i < data.size(); i++) {
if (item == data.at(i)) {
return i;
}
}
return -1;
}
void erase(vector<int>& data, int pos) {
for (unsigned i = pos; i < data.size() - 1; i++) {
data.at(i) = data[i+1];
}
data.pop_back();
}
void insert(vector<int>& data, int pos, int value) {
int last = data.size() - 1;
data.push_back(data.at(last));
for (int i = last; i > pos; i--) {
data.at(i) = data.at(i - 1);
}
data.at(pos) = 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
Start Repl.it and copy the following code into the code editor.
#include <iostream>
using namespace std;
// Prints a number and a string
void print(double num, string str);
// Prints a string and a number
void print(string str, double num);
int main() {
// Enter your function calls here
return 0;
}
// Define your functions here
Add a function definition for each of the function prototypes.
You may choose how to define your functions as long as each one prints both parameter values.
Inside main(), add a statement to call each of the functions you defined, using any number or string you prefer.
Compile your code to make sure it has correct syntax and expected output.
Once satisfied with your code, copy your code into a text editor, save the file as "overload.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.
Example Completed Program
#include <iostream>
using namespace std;
// Prints an number and a string
void print(double num, string str);
// Prints a string and a number
void print(string str, double num);
int main() {
print(42.0, "Hello");
print("Hello", 42.0);
return 0;
}
// Define your functions here
void print(double num, string str) {
cout << "number: " << num << ", string: " << str << endl;
}
void print(string str, double num) {
cout << "string: " << str << ", number: " << num << endl;
}
Reviewing Preprocessor, include and Separate Files
When C++ source code gets translated into machine code, several steps occur before compiling
One of those steps runs a tool known as the preprocessor
The preprocessor scans the file from top to bottom looking for lines that begin with # (hash symbol) and end with a newline
Each such line is known as a preprocessor directive
Preprocessor directives are not program statements, but tell the preprocessor to modify the file in some way before compilation
The most commonly-used preprocessor directive is #include, known as an include directive
The #include tells the preprocessor to replace that line by the contents of a given filename
We have been using the #include directive since we started:
#include <iostream>
It turns out we can include our own files into other program files
Syntax:
#include "myfile.h"
By convention, we use a .h suffix for any file that will be included in another file
The h is short for header, to indicate that the file is intended to be included at the top (or header) of other files
Separating Files
In C++, each program can have only onemain() function
To prevent the main file from becoming too large, we often separate various functions from the main() function
Then any functions or classes needed by main are added using the #include preprocessor directive
To demonstrate, we remove the main() function from last weeks example squarelog program as shown below
Notice that the two files are reconnected by the preprocessor directive
#include "squarelog.h"
We can still compile using the same process we have been using
squarelog.h
#ifndef SQUARELOG_H
#define SQUARELOG_H
#include <iostream>
using namespace std;
const int ANSWER = 42;
// Returns the square of a number
double square(double number);
// Displays a message to the console
void log(string funName, double value);
#endif
squarelog.cpp
#include <iostream>
#include "squarelog.h"
using namespace std;
int main() {
double number = 5;
log("main", number);
double result = square(5);
log("main", result);
return 0;
}
double square(double number) {
log("square", number);
double result = number * number;
log("square", result);
return result;
}
void log(string funName, double value) {
cout << "In " << funName << "() the value is ";
cout << value << endl;
}
In this exercise we explore the use of separate compilation using include directives.
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
Start Repl.it and copy the following code into the code editor.
Inside the main file, add an include directive for the file print.h.
Compile your code to make sure it has correct syntax. Run the code and verify you still see:
int: 42
double: 42
int: 97
string: abc
Once satisfied with your code, copy your code into two separate text files: print.h and print.cpp. submit both files 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.
There is no universal standard for comment layout, but we use a style commonly used with many programming languages:
Block comments start with /** and end with */
The first line explains the idea or purpose of the function, not how it is coded
An @param entry explains each parameter
An @return entry describes the return value
The following example has a fully commented function
Notice that the example does NOT include the program file block comment required for homework
Example Code with Fully Commented Functions
#include <iostream>
using namespace std;
/**
Returns the square of a number
@param number The number to square
@return the square of number
*/
double square(double number);
/**
Displays a message to the console
@param funName The name of the function
@param value The value to display
*/
void log(string funName, double value);
int main() {
double number = 5;
log("main", number);
double result = square(5);
log("main", result);
return 0;
}
double square(double number) {
log("square", number);
double result = number * number;
log("square", result);
return result;
}
void log(string funName, double value) {
cout << "In " << funName << "() the value is ";
cout << value << endl;
}
Using Doxygen
The purpose of the comment layout is to produce hyperlinked web pages describing your program
The standard program to produce the web pages is called Doxygen
In this exercise we format your code to an acceptable style.
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.
/**
CS-11 Asn 6: Calculates the area of a circle and the volume of a sphere.
@file sphere.cpp
@author Ed Parrish
@version 1.1 3/17/20
*/
#include <iostream>
#include <cmath>
using namespace std;
const double PI = 3.14159;
/**
Returns the area of a circle with the specified radius.
@param radius The radius of the circle.
@return The area of the circle.
*/
double area(double radius);
/**
Returns the volume of a sphere with the specified radius.
@param radius The radius of the circle.
@return The volume of the sphere.
*/
double volume(double radius);
// Controls operation of the program.
int main(void) {
double radius_of_both, area_of_circle, volume_of_sphere;
cout << "Enter a radius to use for both a circle\n"
<< "and a sphere (in inches): ";
cin >> radius_of_both;
area_of_circle = area(radius_of_both);
volume_of_sphere = volume(radius_of_both);
cout << "Radius = " << radius_of_both << " inches\n"
<< "Area of circle = " << area_of_circle
<< " square inches\n"
<< "Volume of sphere = " << volume_of_sphere
<< " cubic inches\n";
return 0;
}
// Returns the area of a circle with the specified radius.
double area(double radius) {
return (PI*pow(radius, 2));
}
// Returns the volume of a sphere with the specified radius.
double volume(double radius) {
return ((4.0/3.0)*PI *pow(radius,3));
}
Select the select Chromium, Webkit or file and press Format!
Feel free to experiment with different styles.
Once satisfied with your code, copy your code into a text editor, save the file as "formatted.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 should quite similar to the example below, within the approved options.
Example Formatted Program
/**
CS-11 Asn 6: Calculates the area of a circle and the volume of a sphere.
@file sphere.cpp
@author Ed Parrish
@version 1.1 3/17/20
*/
#include <iostream>
#include <cmath>
using namespace std;
const double PI = 3.14159;
/**
Returns the area of a circle with the specified radius.
@param radius The radius of the circle.
@return The area of the circle.
*/
double area(double radius);
/**
Returns the volume of a sphere with the specified radius.
@param radius The radius of the circle.
@return The volume of the sphere.
*/
double volume(double radius);
// Controls operation of the program.
int main(void) {
double radius_of_both, area_of_circle, volume_of_sphere;
cout << "Enter a radius to use for both a circle\n"
<< "and a sphere (in inches): ";
cin >> radius_of_both;
area_of_circle = area(radius_of_both);
volume_of_sphere = volume(radius_of_both);
cout << "Radius = " << radius_of_both << " inches\n"
<< "Area of circle = " << area_of_circle
<< " square inches\n"
<< "Volume of sphere = " << volume_of_sphere
<< " cubic inches\n";
return 0;
}
// Returns the area of a circle with the specified radius.
double area(double radius) {
return (PI * pow(radius, 2));
}
// Returns the volume of a sphere with the specified radius.
double volume(double radius) {
return ((4.0 / 3.0) * PI * pow(radius, 3));
}