8: Functions

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?

8.1: Cooperative Quizzes

Quiz Part 1: Individual Readiness Assessment

Quiz Part 2: Team Readiness Assessment (20m)

Quiz Appeals

8.2: Function basics

Reviewing function basics

Defining Functions

Example Function Definitions

#include <iostream>
using namespace std;

void ShowFToC(double fDegrees) {
    double cDegrees = 5.0 / 9 * (fDegrees - 32);
    cout << fDegrees << " degrees Fahrenheit is "
         << cDegrees << " degrees Celsius." << endl;
    return;
}

int main() {
    double fTemperature;

    cout << "Enter a temperature in Fahrenheit: ";
    cin >> fTemperature;
    ShowFToC(fTemperature);

    return 0;
}

Parameters

CA 8.2: Challenge activities

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

If so, list the CA numbers in Chat

Exercise 8.2: Coding function basics (15m)

In this exercise we write function definitions with parameters.

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 code editor.
    #include <iostream>
    using namespace std;
    
    //Function definition goes here
    
    int main() {
        int length = 1;
    
        do {
            cout << "\nI will print squares for you!\n";
            cout << "Enter the length of a side (-1 to quit): ";
            cin >> length;
            //code to call function
        } while (length > 0);
        cout << "Thanks for \"squaring\" with me!" << endl;
    
        return 0;
    }
    
  2. Compile and run your code to make sure you added the code correctly.

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

    I will print squares for you!
    Enter the length of a side (-1 to quit): 5
    
    I will print squares for you!
    Enter the length of a side (-1 to quit): -1
    Thanks for "squaring" with me!
    
  3. Write a function that prints squares named printSquares() with an int parameter named size that returns nothing.

    Use the following code inside the function.

    for (int row = 1; row <= size; row++)
    {
        for (int col = 1; col <= size; col++)
        {
            cout << "*";
        }
        cout << endl; // newline before next row
    }
    
  4. Call your function inside the while loop so that it will print out a square given the user input for the length of a side.
  5. Run the program again and verify you see results like the following:
    I will print squares for you!
    Enter the length of a side (-1 to quit): 5
    *****
    *****
    *****
    *****
    *****
    
    I will print squares for you!
    Enter the length of a side (-1 to quit): -1
    Thanks for "squaring" with me!
    
  6. Once satisfied with your code, copy it into a text editor, save the file as "squarefun.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.

8.3: Return

Reviewing return

Example Code

#include <iostream>
using namespace std;

int add(int a, int b) {
    int sum = a + b;
    return sum;
}

int main() {
    cout << "Enter two numbers to add: ";
    int num1, num2;
    cin >> num1 >> num2;
    int total = add(num1, num2);
    cout << "Sum=" << total << endl;

    return 0;
}

Return Statement

Returning a Value from a Function

Returning values from a function call

Returning an Expression

CA 8.3: Challenge activities

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

If so, list the CA numbers in Chat

Exercise 8.3: Coding return (10m)

In this exercise we code a function with a return statement.

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;
    
    // Define function here
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. Write the definition of a function named sub that receives two int numbers and returns an int value, like the add() function.
    returnType sub(two_int_parameters)
    
  3. Add a pair of curly braces for the function body: { }.
  4. Inside the function body, subtract the second parameter from the first and return the value.
  5. Compile and run your code. What do you see when you compile and run? (click here) Click to show answer
  6. Inside the main() function, add these statements:
        cout << "Enter two numbers to subtract: ";
        int num1, num2;
        cin >> num1 >> num2;
        int diff = sub(num1, num2);
        cout << "Difference=" << diff << endl;
    
  7. Compile and run your program and verify the output looks like:
    Enter two numbers to subtract: 3 1
    Difference=2
    
  8. Once satisfied with your code, copy your code into a text editor, save the file as "sub.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.

8.4: Reasons for defining functions

Reviewing reasons for defining functions

Program Design

Function Stubs

Example Function Stub

double calcUnitPrice (int diameter, double price) {
    cout << "FIXME: Calculate unit price" << endl;
    return 1; // dummy value
}

Avoiding Redundant Code

CA 8.4: Challenge activities

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

If so, list the CA numbers in Chat

Exercise 8.4: Simplifying code with functions (10m)

In this exercise we simplify code using 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;
    
    int main() {
        double powerConsumptionApp1;
        double powerConsumptionApp2;
        double powerConsumptionApp3;
        double hoursOfUse1;
        double hoursOfUse2;
        double hoursOfUse3;
        double energyPerDay1;
        double energyPerDay2;
        double energyPerDay3;
        double totalEnergyConsumed;
    
        powerConsumptionApp1 = 600.85;
        hoursOfUse1 = 12.8;
        energyPerDay1 = (powerConsumptionApp1 * hoursOfUse1) / 1000;
    
        powerConsumptionApp2 = 1800.45;
        hoursOfUse2 = 0.45;
        energyPerDay2 = (powerConsumptionApp2 * hoursOfUse2) / 1000;
    
        powerConsumptionApp3 = 70;
        hoursOfUse3 = 1.5;
        energyPerDay3 = (powerConsumptionApp3 * hoursOfUse3) / 1000;
    
        totalEnergyConsumed = energyPerDay1 + energyPerDay2 + energyPerDay3;
    
        cout << "The total energy consumed per day is "
             << totalEnergyConsumed
             << "." << endl;
    
        return 0;
    }
    
  2. Compile your code to make sure it has correct syntax. Run the code and verify you see the following output.
    The total energy consumed per day is 8.60608.
    
  3. Before main(), add the following function.
    double ComputeEnergyConsumed(double power, double hours) {
       return (power * hours) / 1000;
    }
    
  4. Using the above function, simplify your program from 35 lines of code to less than 25 lines (20 is easily possible), while keeping the same output and following good programming style like blank lines (5 minimum) around functions and other areas of code. Magic numbers are allowed in this exercise since the original code has magic numbers.

    Bonus to the team with the least number of lines of code that follows good style.

  5. Once satisfied with your code, copy your code into a text editor, save the file as "simple.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.

8.5: Function flow

Reviewing function flow

Flow of control for a function call

Function Call Flow

Flow of control for a function call
  1. Every program starts executing at the start of the function main().
  2. When reaching a function call, arguments are copied to the parameters.
  3. Function code executes until reaching a return statement.
  4. Return statement returns a value to the function call.
  5. Calling function continues after the function returns.

Tracing Code

Example Code with Function Call

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

int add(int a, int b) {
    int sum = a + b;
    return sum;
}

int main() {
    cout << "Enter two numbers to add: ";
    int num1, num2;
    cin >> num1 >> num2;
    int total = add(num1, num2);
    cout << "Sum=" << total << endl;

    return 0;
}

CA 8.5: Challenge activities

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

If so, list the CA numbers in Chat

Exercise 8.5: Tracing flow (10m)

Be the computer

Be the computer

In this exercise we trace the flow of control when in a program with a function call.

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. Create a text file named trace.txt.
  2. In the trace.txt file, list the line numbers of each statement of the following program in the order the lines are executed. For example, if main() starts on line 9, statements are executed as follows:
    9, 10, 11, 12, ...
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    #include <iostream>
    using namespace std;
    
    int add(int a, int b) {
        int sum = a + b;
        return sum;
    }
    
    int main() {
        cout << "Enter two numbers to add: ";
        int num1, num2;
        cin >> num1 >> num2;
        int total = add(num1, num2);
        cout << "Sum=" << total << endl;
    
        return 0;
    }
    

    Do not bother to list blank lines or lines containing only a curly brace (}) of a function definition.

  3. Review the code trace with another student in the class. Then add a comment to the top of the trace.txt file that contains the name of the team members with whom you reviewed the code, like:
    Reviewed trace with team members: Fred George, ...
  4. Save the trace.txt to submit to Canvas with the rest of the exercise files for the week.

When finished with your trace click hereClick to show answer to verify.

8.6: Scope

Reviewing variable scope

Scope

Passing Arguments to Function Parameters

Passing arguments in a function call

Example code with variables in different scopes

#include <iostream>
using namespace std;

const double PI = 3.14159265;

double circleArea(double radius) {
    double area = PI * radius * radius;
    return area;
}

int main() {
    cout << "Enter the radius of a circle: ";
    double radius = 0.0;
    cin >> radius;

    double area = circleArea(radius);
    cout << "The circle area is " << area << endl;

    return 0;
}

Global Variables and Constants

Programming Style: No Global Variables

Exercise 8.6: Exploring global variables (10m)

In this exercise we examine some of the hazards of using global variables.

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 explain your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Create a text file named globalout.txt.
  2. Look at the following code without running it.
    int x, y, z;
    
    int fun(int a, int  b) {
        int x;
        x = a + 2;
        a = a * 3;
        b = x + a;
        return b;
    }
    
    int main( ) {
        x = 1;
        int y = 2;
        z = 3;
        y = fun(y, x);
        cout << x << ' ' << y << ' ' << z << endl;
        return 0;
    }
    
  3. As a team, trace the code and decide on the output of the code without running it.
  4. Type the expected output into the gobalout.txt file.
  5. Save the globalout.txt file to submit to Canvas with the rest of the exercise files for the week.

Reviewing function prototypes

Example Code

#include <iostream>
using namespace std;

// Returns the square of a number
double square(double number);

// Displays a message to the console
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;
}

Exercise 8.7: Coding function prototypes (10m)

In this exercise we add function prototypes to a program.

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;
    
    int FunA(int num) {
        if (num > 0) {
            FunB(--num);
        }
        return 42;
    }
    
    int FunB(int param) {
        return FunA(--param);
    }
    
    int main() {
        int num = FunA(3);
        cout << num << endl;
        return 0;
    }
    
  2. Compile and run the code to see the error produced.
  3. Add function declarations (function prototypes) to resolve the errors.
  4. After resolving the error, reverse the order of FunA() and FunB() and compile again.
  5. Add function declarations (function prototypes) to resolve the errors, if any.
  6. Move FunA() and FunB() below main() and compile again.
  7. Add function declarations (function prototypes) to resolve the errors, if any.
  8. Once satisfied your code will work when defining functions after main(), copy your code into a text editor, save the file as "proto.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.