Welcome to Lesson 17!


Learning Objectives
By the end of today's class, you should know...
  • What is a void function and how does it differ from a non-void function?
  • What is a function prototype and what is its purpose?
  • Where do you place a function prototype in your program?
  • What is the syntax of a function prototype?
  • How do you properly comment a function?
  • How can you call one function inside of another function?

Announcements

  • Midterms returned at the end of class
    • As: 26 (6 100% scores)
    • Bs 5
    • Cs: 3
    • Ds: 4
    • Fs: 3
  • Next Quiz one week from Thursday
  • No Lab on Friday due to Thanksgiving Holiday


Review Activity


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


Void Functions

  • Previously we looked at functions that returned one value
  • Functions returning a value use a return statement
    return result;
  • A function that returns no value is called a void function
  • In C++, void functions are defined like functions that return a value
  • However, the keyword void replaces the return type
  • For example, what do you notice that is different about the following?
    void displayDegrees(double degreeFarenheit) {
        double degreeCelsius = 5.0 / 9 * (degreeFarenheit - 32);
        cout << degreeFarenheit
             << " degrees Fahrenheit is equivalent to "
             << degreeCelsius << " degrees Celsius." << endl;
        return;
    }
    
  • There are only two differences between definitions for void functions and other functions:
    • void return type
    • return statement is optional and does not specify a value if used
  • If no return type is specified, the function returns after executing the last statement
  • Here is an example program using the void function shown above

Example Program With a void Function


#include <iostream>
using namespace std;

void displayDegrees(double degreeFarenheit) {
    double degreeCelsius = 5.0 / 9 * (degreeFarenheit - 32);
    cout << degreeFarenheit
         << " degrees Fahrenheit is equivalent to "
         << degreeCelsius << " degrees Celsius." << endl;
    return;
}

int main() {
    double fTemperature;

    cout << "Enter a temperature in Fahrenheit: ";
    cin >> fTemperature;
    displayDegrees(fTemperature); //Notice function call without assigning result to variable

    return 0;
}

When to Write void Functions

  • When we use a non-void function, we are asking a question
  • The function returns a value in response to our question
    cout << sqrt(9.0);
    
  • When we use a void function, we are giving the computer a command
    displayDegrees(212);
  • We do not expect or receive an answer

Common Errors With void Functions

  • Note that we cannot call a void function from a cout statement
  • For example, the following causes a compile error:
    cout << displayDegrees(fTemperature); // NO!
  • The reason is that a void functions does not return a value and cout has nothing to print
  • Similarly, we cannot call a void function in an assignment statement:
    double temp = displayDegrees(fTemperature); // NO!
  • There is nothing to assign to the variable temp

Activity 17.1: Printing Squares (10 pts!)

  • Remember our programs that used nested for loops to print out shapes.
  • Let's write a similar program with a function that prints squares of different sizes for our user.
  • Open up CodeBlocks and create a new C++ file called squares.cpp.
  • Then, copy and paste the starter code into your file, save it and run it to make sure everything is working properly.
#include <iostream>
using namespace std;

//Your function goes here

int main() {
    int length;

    while (length != -1) {
        cout << "I will print squares for you!\n";
        cout << "Please enter the length of one side of the square or -1 to quit: ";
        cin >> length;
        //code to call function

    }
    cout << "Thanks for \"square\" dancing with me!" << endl;

    return 0;
}
  • Now, write a function that prints squares called printSquares(). Your function should take in an integer argument for the length of one side of the square and should return nothing.
  • 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.
  • Run the program again. Does it print out a square?
  • When you are finished, upload your squares.cpp file to Catalyst.
  • The output of your program should look identical to the sample output below (except user input will vary).


Function Prototypes

  • C++ allows you to declare functions without defining them
  • Function declarations (prototypes) have the function heading without the function body
  • The general syntax for declaring a function is:
    returnType functionName(parameter1, ..., parametern);
    
  • Where:
    • returnType: the type of the value returned
    • functionName: the name you make up for the function
    • parameterx: the input values, if any
  • As an example, we can declare a function to calculate the square of a number like this:
    double square(double number);
  • By declaring a function, the compiler can resolve a function call made inside main()
  • Thus, we can reorganize our programs to place function definitions after main()
  • For now the use of function prototypes is optional
  • However, there are times in C++ when you need to use function prototypes
  • Note that if you use function prototypes, you place the block comments before the prototypes and not the definitions
  • You can see this new function organization in the following example

Example Program with Function Prototypes



#include <iostream>
using namespace std;

int square(int number);

void printSquare(int length);

int main() {
    cout << "Enter a number to square: ";
    int side;
    cin >> side;
    cout << "The square of the number is << square(side) << endl;
    cout << "As you can see for yourself!\n";
    printSquare(side);
} int square(int number) { int result = number * number; return result; } void printSquare(int length) { for (int i = 0; i < length; i++)
    {
        for (int j = 0; j < length; j++)
        {
            cout << "*";
        }
        cout << endl;
}

Note that the function signatures must match in regards to data types of the parameters and return values!

Okay to do:

//prototype
void printDate(int month, int day, int year);

//function
void printDate(int m, int d, int y) {
    cout << "The date: " << m << "/" << d << "/" << y << endl;
    return;
}

Not okay to do:
//prototype
void printDate(int month, int day, int year);

//function
void printDate(double month, double day, double year) {
    cout << "The date: " << month << "/" << day << "/" << year << endl;
    return;
}

Programming Style Requirements for Functions

Commenting Functions

  • Good programming style dictates that each function have a comment, stating what it does.
  • There is no universal standard for comment layout.
    • Often in C++, you will see a comment written underneath each function prototype
  • The following example has commented functions

Example Program with Commented Functions



#include <iostream>
using namespace std;

double square(double number);
//Multiplies a number by itself

void printDate(int month, int day, int year);
//Prints a date in the m/d/y format

int main() { double number = 5;
    double result = square(number);
    cout << "The square of 5: " << result << endl;
    cout << "The square of 3: " << square(3) << endl;
    int month = 4;
    int day = 2;
    int year = 1845;
    printDate(month, day, year);
    printDate(3, 26, 2015);
    return 0; } double square(double number) { double result = number * number; return result; } void printDate(int month, int day, int year) { cout << "The date: " << month << "/" << day << "/" << year << endl; return; }


Activity 17.2: Prototypes and Comments (10 pts)
  • Open up a text editor and create a new file named prototypes.txt.
  • In the file, write the prototypes for the following functions.
  • Then below each prototype, add an appropriate comment in the style shown above.
double areaTriangle(double base, double height) {
    double area = 0.5 * base * height;
    return area;
}

string myName(string firstName, char initial, string lastName) {
    string fullName = firstName + " " + initial + ". " + lastName;
    return fullName;
}

bool isLeapYear(int year) {
    if (year % 4 == 0) {
        return true;
    } else {
        return false;
    }
}
  • When you are finished, submit your prototypes.txt to Catalyst.


Functions Calling Functions
  • Functions may call other functions
  • Within the body of one function, we can call another function call
  • Functions can call other functions as often as needed
  • We are already doing this when main() calls a function
  • The following program calls a "helper" function to help calculate the BMI.
  • Because calculating the BMI is a somewhat complicated process, it is helpful to create a second function to do part of the work for us.
  • The heightToSquareInches function handles turning the height from feet and inches (such as 5'8") into inches squared (such as 68"2).

Example of Functions Calling Functions


#include <iostream>
using namespace std;


    
    
double calculateBMI(int heightinFeet, int heightInInches, double weight);
//
Calculates a user's Body Mass Index

int heightToSquareInches(int feet, int inches);

//Converts height in feet and inches to height in inches squared

int main() { const double WEIGHT = 135.5;
    const int HEIGHT_FEET = 5;
    const int HEIGHT_INCHES = 8;
    double bmi = calculateBMI(HEIGHT_FEET, HEIGHT_INCHES, WEIGHT); cout << "Your BMI is: " << bmi << endl; return 0; }
double calculateBMI(int heightInFeet, int heightInInches, double weight) {
    int heightInches2 = heightToSquareInches(heightInFeet, heightInInches);
    double bmi = weight / heightInches2 * 703;
    return bmi; }

//helper function to convert the height from feet and inches to inches squared

int heightToSquareInches(int feet, int inches) {
    int heightInInches = feet * 12 + inches;
    int heightInInchesSquared = heightInInches * heightInInches;
    return heightInInchesSquared;

}


Wrap Up
  • Answer the questions from today's learning objectives

Upcoming Assignments

  • Assignment 17 due Thursday at 3:20pm on Catalyst
  • No Lab on Friday due to Holiday