9: Functions 2

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?

9.1: Cooperative Quizzes

Quiz Part 1: Individual Readiness Assessment

Quiz Part 2: Team Readiness Assessment (20m)

Quiz Appeals

9.2: Pass by Reference

Reviewing Pass by Reference

Example of Value Parameters

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

int mystery(int param) {
    cout << "param=" << param << endl;
    param = param * 2;
    return param;
}

int main() {
    int num = 2;

    cout << "At first, num=" << num << endl;
    int result = mystery(num);
    cout << "After calling, num=" << num << endl;
    cout << "And result=" << result << endl;

    return 0;
}

Implementing Pass by Reference

Example of Reference Parameters

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

int mystery(int& param) {
    cout << "param=" << param << endl;
    param = param * 2;
    return param;
}

int main() {
    int num = 2;

    cout << "At first, num=" << num << endl;
    int result = mystery(num);
    cout << "After calling, num=" << num << endl;
    cout << "And result=" << result << endl;

    return 0;
}

Comparing Call-by-Reference vs Call-by-Value

call-by-reference vs. call-by-value
Image source: penjee.com

Another Call-by-Reference versus Call-by-Value Analogy

Mixed Parameter Lists

When to Use Reference Parameters

CA 9.2: Challenge activities

Any problems with any of these Challenge activities? (Zybooks sign in)

If so, list the CA numbers in Chat

Exercise 9.2: Coding Pass by Reference (5m)

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

  1. 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;
    }
    
  2. 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.

  3. Change your program by adding the four ampersands (&) circled below:

    Program using pass by reference

    The ampersands tell C++ to use call-by-reference when passing parameter values.

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

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

9.3: Functions with Vector Parameters

Reviewing Functions with Vector Parameters

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

Removing an Element

Inserting an Element

CA 9.3: Challenge activities

Any problems with any of these Challenge activities? (Zybooks sign in)

If so, list the CA numbers in Chat

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

  1. Download the starter code and save it to a convenient location like the Desktop.

    algorithms.cpp

  2. Open your code in a text editor and copy it to the code editor of Repl.it
  3. Compile and run your program to make sure you do not have any errors so far. When run you should see output like:
    Vector Algorithms
    
    Vector data:
    0. Exit program
    1. Find item
    2. Remove item
    3. Insert new item
    Choice (0-3): 0
    
    Goodbye!
    

    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.

  4. 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;
    }
    
  5. 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:
    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): 0
    
    Goodbye!
    

    Notice the list of numbers printed, which are the numbers stored in the vector.

  6. 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;
    }
    
  7. 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.

  8. 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();
    }
    
  9. 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:
    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): 2
    Position to remove value: 2
    
    Vector data: 5 7 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 number for the position (index) is now gone. In our example, the number 4 is gone from position 2.

  10. 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;
    }
    
  11. 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.

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

9.4: Overloaded Functions

Reviewing Overloaded Functions

Example Code

#include <iostream>
using namespace std;

void print(int num);
void print(double num);
void print(string str);

int main() {
    print(42);    // first
    print(42.0);  // second
    print('a');   // Which function does this call? Why?
    print("abc"); // third

    return 0;
}

void print(int num) {
   cout << "int: " << num << endl;
}

void print(double num) {
   cout << "double: " << num << endl;
}

void print(string str) {
   cout << "string: " << str << endl;
}

CA 9.4: Challenge activities

Any problems with any of these Challenge activities? (Zybooks sign in)

If so, list the CA numbers in Chat

Exercise 9.4: Coding Overloaded Functions (10m)

In this exercise we code overloaded functions.

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

  3. Inside main(), add a statement to call each of the functions you defined, using any number or string you prefer.
  4. Compile your code to make sure it has correct syntax and expected output.
  5. 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 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.

9.5: Preprocessor, include and Separate Files

Reviewing Preprocessor, include and Separate Files

Separating Files

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;
}

#include Guards

More Information

Exercise 9.5: Coding with #include (10m)

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

  1. Start Repl.it and copy the following code into the code editor.
    #include <iostream>
    using namespace std;
    
    void print(int num);
    void print(double num);
    void print(string str);
    
    int main() {
        print(42);
        print(42.0);
        print('a');
        print("abc");
    
        return 0;
    }
    
    void print(int num) {
       cout << "int: " << num << endl;
    }
    
    void print(double num) {
       cout << "double: " << num << endl;
    }
    
    void print(string str) {
       cout << "string: " << str << endl;
    }
    
  2. Compile your code to make sure you copied it correctly. Run the code and verify you see:
    int: 42
    double: 42
    int: 97
    string: abc
    
  3. In repl.it, add a second file named print.h.
    1. Next to Files, click the page icon with a '+' sign on it.
    2. Type the file name in the box that appears underneath "Add file".

    Add file menu in repl.it

  4. Copy the include directives and move the function prototypes to the new file.
  5. Add the #include guards to the print.h file:
    #ifndef PRINT_H
    #define PRINT_H
    
    ... (function prototypes)
    
    #endif
    
  6. Inside the main file, add an include directive for the file print.h.
  7. 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
    
  8. 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 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.

9.6: Programming Style Requirements for Functions

Camel Case

Naming Functions

Commenting Functions

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

More Information

Exercise 9.6: Styling code (10m)

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.

Specifications

  1. Open the C++ online code formatter and copy the following code into the editor window:
    
    /**
        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));
    }
    
  2. Select the select Chromium, Webkit or file and press Format! Feel free to experiment with different styles.
  3. 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 hereClick to show answer to verify. Code should quite similar to the example below, within the approved options.