Home‎ > ‎CIS22ATTh‎ > ‎cis-22a-tth-schedule‎ > ‎

lesson16

Welcome to Lesson 16!


Learning Objectives
By the end of today's class, you should know...
  • What is the difference between a global and local variable?
  • How do you trace a function call?
  • What are some style requirements for functions
  • More function practice

Announcements

  • Midterm 2 after the break.
  • Yes, there is homework for tonight!
  • Last day to drop with a "W" is this Friday

Review Activity

With a partner, answer the following questions:

  • Label the components of the following function:

double calc_area_circle(int radius) {

    double area = 3.14 * radius * radius;

    return area;

}

Function Name:

Return type:

Parameter(s):

  • Write a correct function call for the above function, passing it the value of 9.5, and storing the result in the cArea variable:

         double cArea = ???????????????????;

    cout << "The area of the circle with radius 9.5 is: " << cArea << endl;

    

Functions Continued

Variable and Parameter Scope

  • A variable declared inside a function can only be used within that function

    Local variable: a variable that can only be accessed within a function or block.

  • Parameters are a local variable and thus can only be used inside the function in which they are declared as well
  • As an example of a local variable, we declared sum inside the add() function:
    int sum = a + b;
    
  • In addition, we declared another variable named total inside main():
    int total = add(num1, num2);
    
  • These variables cannot be accessed outside the function they were declared within

Scope

  • The area of code that a variable can operate within is known as it's scope

    Scope: the enclosing area within which a variable exists

  • Because of scope, we can use variables with the same name in different functions
  • To send information to a function we must include a parameters:
    int add(int a, int b)
    
  • When the function call is made, we send the arguments to the parameters:
    add(num1, num2)
    
  • The values of num1 and num2 are copied to the parameter variables a and b

Example of Scope

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

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

int sub(int a, int b) {
    int sum = a - b; //okay to name this variable sum?
    return sum;
}

int main() { cout << "Enter two numbers to add and subtract: "; int num1, num2; cin >> num1 >> num2; int total = add(num1, num2);
    int diff = sub(num1, num2);
    cout << "Sum=" << total << " Difference=" << diff<< endl;
    //Why can't I do this?
//cout << sum << endl;
  return 0; }

Flow of Control for a Function Call

  • To use functions well, we must understand their flow of control
  • In our example, the program starts executing in the main() function
  • When our program gets to the following statement, it stops executing in main() and jumps to our function:
    int total = add(num1, num2);
    
  • The program executes the statements in the function and then returns to the statement from which it jumped
  • When the function returns, the returned value replaces the function call
  • After returning, the program completes processing the calling statement and then moves on to the next statement
  • In our example, the statement saves the returned value in the variable: total
  • Every time the flow of control reaches a function call, the program:
    1. Temporarily stops executing in the current function
    2. Jumps to the called function and executes the statements of that function
    3. Returns to the point in the code from which it jumped

Function Call Flow


  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.

Activity 16.1: Tracing a Function Call (10 pts)

  1. Create a text file named trace.txt.
  2. In the trace.txt file, list the line numbers of each statement of your program from Activity 15.2 in the order the lines are executed. For example, if main() starts on line 9, statements are executed as follows:
    9, 10, 11, 12, ...
    

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

  3. Review the hand trace with another student in the class. Then add a comment to the top of the file that contains the name of the person with whom you reviewed the code, like:
    Reviewed trace with Fred George.
  4. Save the trace.txt to submit to Catalyst

Some Style Requirements for Functions

  • Consider again our example function

#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;
}
  • Note the placement of the curly braces
  • There are two common styles of curly brace placement for functions:
    1. Place the opening brace on the same line as the function heading:
      int myFunction() {
          // statements of the function
      }
      
    2. Place the opening brace under and lined up with the first letter of the return type:
      int myFunction()
      {
          // statements of the function
      }
      
  • We can use either style as long as we are consistent
  • Also notice the indentation of the statements inside the function
  • As before, we always indent 3-4 more spaces after an opening curly brace
  • After the closing curly brace, we no longer indent the extra 3-4 spaces
  • Indenting makes it easier to see the block of code
  • In addition, function names always start with a lower case letter like variables
  • We can tell the difference between function and variable name because functions have parenthesis


Activity 16.2: My Salary (10 pts)

  • Open up CodeBlocks and create a new C++ file called salary.cpp.
  • Copy and paste the starter code below into the file.
  • NOTE: Do not change the starter code! All you need to do is add to it.
/*
* Name
* Section
*/

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

//write your functions here

int main() {
   
    int hours;
    double hourly_wage;
    double weekly_salary = 0;
    double monthly_salary = 0;
    double yearly_salary = 0;
   
    cout << "This program will calculate your weekly, monthly and yearly salary!\n";
    cout << "Please enter your hourly wage: ";
    cin >> hourly_wage;

    cout << "Please enter the number of hours you work each week: ";
    cin >> hours;

    //call functions below
   

    weekly_salary = //function call goes here
    monthly_salary = //function call goes here
    yearly_salary = //function call goes here
   
    cout << fixed << setprecision(2);

    cout << "You make $" << weekly_salary << " per week.\n";
    cout << "You make $" << monthly_salary << " per month.\n";
    cout << "You make $" << yearly_salary << " per year.\n";

}

  • Now write three functions as follows and place them above main:
    • weeklySalary()
Takes in an integer argument for the number of hours worked each week
Takes in a double argument for the hourly wage
Returns a double for the weekly salary
    • monthlySalary()
Takes in an integer argument for the number of hours worked each week
Takes in a double argument for the hourly wage
Returns a double for the monthly salary
    • yearlySalary()
Takes in an integer argument for the number of hours worked each week
Takes in a double argument for the hourly wage
Returns a double for the yearly salary
Assume that you work 50 weeks a year (2 weeks vacation)
  • Add a function call and store the result as the appropriate variable.
weekly_salary = //function call goes here
monthly_salary = //function call goes here
yearly_salary = //function call goes here
  • Now, run your code and verify that it prints the correct values for each salary type.
  • When you are finished, upload your file to Catalyst.
  • Your output should look identical to the following (except user input will vary):





Midterm 2

Wrap Up

  • With your partner, answer the following questions:

1. What is output by the following program? (Do not run the code -- work it out by hand)


#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;
}
  1. At first, num=2
    param=2
    After calling, num=4
    And result=4
    
  2. At first, num=2
    param=4
    After calling, num=4
    And result=4
    
  3. At first, num=2
    param=2
    After calling, num=2
    And result=4
    
  4. None of these


2. Write the following functions:

  • areaRectangle
    • Takes in a double for the length and width
    • returns the area of the rectangle as a double
  • areaTriangle
    • Takes in a double for the base and height
    • returns the area of the triangle as a double
  • mpg
    • takes in an integer for the miles and the gallons
    • returns the miles per gallon as a double

3. How would you call the following function inside of main:


double battingAverage(int hits, int timesAtBat)
{
    double average = (double) hits/timesAtBat;
    return average;
}

int main()
{
    int numHits, numAtBat;
    double average;

    cout << "Please enter the number of hits you have this season: ";
    cin >> numHits;

    cout << "Please enter the number of times you have been at bat: ";
    cin >> numAtBat;

    //call the function here

    return 0;
}


Upcoming Assignments
  • Assignment 16 due Tuesday, November 22 at 3:20pm on Catalyst
  • Lab 7 due Friday at midnight

Comments