Welcome to Lesson 16!


Learning Objectives

By the end of today's class, you should know...
  • How do you write a simple function?
  • What are the different parts of the function signature and what is the purpose of each one?
    • name of function
    • return type
    • parameter list
  • How do you return a value from a function?
  • What is a local vs global variable?
  • How do you "call" a function?


Announcements

  • Midterm 2 one week from today
    • Similar in format to midterm 1
    • ~12 short answer/multiple choice questions
    • 1 complete program
    • Covers material from Lesson 9 - today's lesson (1 simple function on the midterm)
  • Don't forget Lab 8 due Friday
  • Quiz 6 after the break
  • Last day to drop with a 'W' is this Friday
    • Please check your current grade on Canvas
    • Better to drop with a 'W' than to get an 'F' in most cases
    • Please feel free to talk to me


Review Activity

With a partner, answer the following questions:

  • Write one line of code to read in the full name input by the user into a string variable named full_name:

string full_name;

cout << “Please enter your full name: ”;

//write your line of code here


  • Write a for loop to print out the below string with each character on its own line. Please use the [] string indexing rather than substr:
string sentence = "Let's grab coffee.";
//write your for loop here





  • What is the advantage of using a do-while loop instead of a while loop?


    The do-while loop guarantees that...


  • Fill in the 2 missing lines of code below to handle the case where a user enters a string instead of the expected numerical input.

    int id;

    cout << "Please enter your student id#: ";

    cin >> id;


    while (                    ) {


        cin.clear();

       

        cout << "Please enter numbers not words.\n";

        cout << "Please enter your student id#: ";

        cin >> id;

    }

  • There is a problem in the below program Add a line of code to avoid this problem:


    #include <iostream>

    using namespace std;

    int main() {

    string name;

    int age;

    cout << "Enter your age: ";

    cin >> age;


    cout << "Enter your full name: ";

    getline(cin, name);

    cout << "Your age: " << age << endl;

    cout << "Your full name: " << name << endl;

    }

Introducing Functions

C++ comes with libraries of predefined functions

  • Example:  sqrt function returns, or computes, the square root of a number:
double the_root = sqrt(9.0);

 

  • The number, 9.0, is called the argument
  • the_root will contain 3.0

Function Calls

  • sqrt(9.0) is a "function call."
  • It invokes, or sets in action, the sqrt function
  • The argument (9), can also be a variable or an expression
  • A function call can be used like any expression:
double bonus =  sqrt(sales) / 10;

cout << "The side of a square with area " << area
         << “ is “
         << sqrt(area);


What functions have we seen so far in this class?

  • pow(base, exponent)
  • sqrt(number)
  • length()
  • substr(index, numChars)
  • getline(cin, stringVariable)
  • setprecision(n)
  • Any others?

What do they all have in common? Notice any similarities in their syntax?

Function Call Syntax

  • Function_name (Argument_List)
  • Argument_List is a comma separated list:  (Argument_1, Argument_2, … , Argument_Last)   

side = sqrt(area);
cout << "2.5 to the power 3.0 is "
         << pow(2.5, 3.0);

Libraries

  • Predefined functions are found in libraries
  • The library must be “included” in  a program to make the functions available
  • An include directive tells the compiler which library header file to include.
  • To include the math library containing sqrt():
        #include <cmath>
  • Newer standard libraries, such as cmath, also require the directive
using namespace std;

Writing Our Own Functions

Grouping Repeated Commands

  • Some of the main() functions in our programs have been getting lengthy and complicated
  • The biggest problem in developing software is managing the complexity of programs
  • We can improve our code by organizing it into smaller pieces known as functions
  • Functions are a key tool in creating easy-to-understand programs that can be changed easily

Video: Chris Bosh Explains Functions

  • After watching the video, what does it mean to write our own functions?

What is a Function?

  • As developers, we need to know how to write and call functions

    Function: a named block of statements that can receive input, perform an action, and optionally return a value

  • Functions are like little programs in our larger program
  • We give each little function commands we want executed
  • We call the function whenever we want the commands executed
  • When the function has finished running, program execution returns to the point just after the code that called the function

Example Application for a Function

  • As an example, recall our test code to validate user input:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main() {
    double input = 0.0;
    do {
        cout << "Enter a positive number: ";
        cin >> input;
        if (cin.fail()) {
            cout << "You must enter digits, not words\n";
            cin.clear();
            cin.ignore(1000, '\n');
            input = -1; // set loop test to fail
        } else if (input <= 0.0) {
            cout << "You must enter a positive number\n";
        }
    } while (input <= 0.0);
    cout << "You entered: " << input << endl;

    return 0;
}
  • What if we need to enter two validated numbers into a program?
  • We want to process the first number after input and then input the second number
  • Doing so, we would end up with code like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
using namespace std;

int main() {
    double input = 0.0;
    do {
        cout << "Enter a positive number: ";
        cin >> input;
        if (cin.fail()) {
            cout << "You must enter digits, not words\n";
            cin.clear();
            cin.ignore(INT_MAX, '\n');
            input = -1; // set loop test to fail
        } else if (input <= 0.0) {
            cout << "You must enter a positive number\n";
        }
    } while (input <= 0.0);

    // Process the input
    cout << "You entered: " << input << endl;

    double input2 = 0.0;
    do {
        cout << "Enter a positive number: ";
        cin >> input2;
        if (cin.fail()) {
            cout << "You must enter digits, not words\n";
            cin.clear();
            cin.ignore(INT_MAX, '\n');
            input2 = -1; // set loop test to fail
        } else if (input <= 0.0) {
            cout << "You must enter a positive number\n";
        }
    } while (input <= 0.0);

    // Process the second input
    cout << "You entered: " << input2 << endl;

    return 0;
}
  • Our program would be easier to write if we could get the second input without repeating the code
  • With functions, we give the list of commands a name and then run the list by calling the name
  • Using functions we keep all the code in one place and avoid duplication
  • Avoiding duplication reduces the complexity of our code and makes it easier to understand and change

Programming Style: Avoid Duplicating Code

  • Duplicate code can lead to problems such as:
    • Long repeated sections that are more difficult to understand than shorter sequences
    • Repetition of largely identical code within which it is difficult to see the different purposes of each section
    • Update problems where we make changes in some sections but overlook making changes in other sections
  • If we find ourselves writing similar code of three or more lines multiple times, we should consider writing a function

Defining a Function

  • In this section we look at function definition syntax and examine a simple example function
  • After we understand the syntax we can write more complicated functions

Function Syntax

  • The general syntax for defining a function is:
    returnType functionName(parameter1, ..., parametern) {
        statements
    }
    
  • Where:
    • returnType: the data type of the value returned
    • functionName: the name you make up for the function
    • parameterx: the input values, if any
    • statements: the list of statements to execute when the function is called
  • Can you identify each of these syntax items in the function we have always used?
    int main() {
        // program statements go here
    }
    

Example Program with a Second Function

  • As an example, the following program has a simple function to add two numbers
  • Notice that the code has two functions: add() and main()
  • The second function is placed before main() so the compiler knows about the function
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;
}

Function Name

  • Every function must have a name that identifies the function
  • Function names follow the same rules as variable names
  • Technically, we can use any valid identifier for a function name
  • However, we should use a name that suggests the action the function performs
  • In our example, add suggests that the function will return the sum of two numbers

Function Structure

  • The first line of a function is known as the function signature
    int add(int a, int b)
    
  • The curly braces {...} contain the function body
  • The function body is the list of statement the function executes when called
  • The function signature describes the name, inputs and output of a function
  • We will look at these features in more detail in the following sections

Parameters

  • When defining a function, it is worth thinking about what helpful action it will perform
  • We can make the function more useful if we give it parameters
  • The parameters for an add function would be the two numbers to sum
  • Read through the following code to identify how the code makes use of the parameters

Example Code with Function Parameters

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

Parameter List

  • We must have parenthesis after a function name
  • Inside the parenthesis, we define a list of zero or more parameters
  • Parameters are the inputs to a function
  • In our example, we have two parameters inside the parenthesis
    int add(int a, int b)
    
  • Parameters are the declaration of a new variable, even though they are declared inside parenthesis
  • Each parameter must have both a type and a name, just like a regular variable
  • If we have more than one parameter, we separate them with commas
  • Any parameter that we declare must be given an argument when we call the function
  • In the following image, the value of arguments num1 and num2 are copied to the parameters a and b

Passing Arguments to Function Parameters


Arguments and Parameters

  • Depending on our background, we might use the term arguments or parameters for the values passed to functions
  • The terminology is not that important
  • However, the way I will use the terms is:
    • A function definition has parameters
      int add(int a, int b) { // a and b are parameters
          // ...
      }
      
    • A function call passes arguments
      add(num1, num2); // num1 and num2 are arguments
      
  • Arguments are values we pass into functions
  • When the argument drops into a function, it lands in a parameter
  • A parameter is just like other variables in the function
    • Except that a parameter gets initialized by an argument
  • The important part is:

    We must pass every function parameter an argument.

  • The arguments must be in the same order as the parameters
  • Also, the argument value must be compatible with the type of the parameter
  • For example, we cannot call add() with: add("Jennifer", "Parrish")



Returning a Value

  • The first word in the function signature is the return type
    int add(int a, int b)
    
  • The return type specifies the type of data the function outputs
  • In our example the return type is an int

Return Statement

  • Functions that return a value must execute a return statement
    return result;
    
  • For instance, our example function add() has a return statement
    int add(int a, int b) {
        int sum = a + b;
        return sum;
    }
    
  • Note that the type of the returned valued must be compatible with the function return type
  • The returned value is substituted for the function call in the calling code
    sum =>[replaces]=> add(num1, num2)
    
  • We must save the returned value if we want to process it later in the program
    int total = add(num1, num2);
    

Returning a Value from a Function

Returning an Expression

  • The value after the word return can be an expression
  • It does not have to be just the name of a variable
  • We could rewrite our return statement to the following:
    return a + b;
    

Multiple return Statments

  • We can have more than one return stattement in a function
  • The first return statement reached is the one executed
  • We might have multiple returns if we have if-statments with alternate actions, like:
    if (x > 400) {
        return 1;
    } else {
        return 0;
    }
    
  • We do not have alternate actions in our simple add function and so have only one return statement

Activity 16.1: Writing a Function (10 pts)

In this exercise we define our own function.

Specifications

  1. Copy the following program into Eclipse, save it as sub.cpp, and then compile and run the starter program to make sure you copied it correctly.
    #include <iostream>
    using namespace std;
    
    // Define function here
    
    int main() {
    
        return 0;
    }
    
  2. Write the signature for a function named sub that receives two int numbers and returns an int value, like we did for the add() function
    returnType sub(two_int_parameters)
    
  3. Add the curly braces for the function body: { }.
  4. Inside the function body, subtract the second parameter from the first and return the value, like we did for the add() function.
        int sum = a + b; // from add() function, CHANGE THIS!
        return sum;
    
  5. Compile and run your code. What do you see when you compile? (click here) Click to show answer
  6. Inside the main() function, enter these statements:
        cout << "Enter two numbers to subtract: ";
        int num1, num2;
        cin >> num1 >> num2;
        int diff = sub(num1, num2);
        cout << "Difference=" << diff << endl;
    

    The fourth line contains the function call.

  7. Compile and run your modified program and verify the output looks like:
    Enter two numbers to subtract: 3 1
    Difference=2
    
  8. Save your sub.cpp file and submit it to Canvas.

Completed Program

When finished, your application should look like the following.




Upcoming Assignments

~Have a Great Weekend!~