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
  • Return midterms at the end of class:
    • As: 20
    • Bs: 12
    • Cs: 5
    • Ds: 4
    • Fs: 3
    • No shows: 1
  • Lab 9 due Friday at midnight
  • Quiz next class! - Functions, functions, functions!

Review Activity

With a partner, write the following functions:
  • Name: mpg
    • takes in an integer for the miles and the gallons
    • returns the miles per gallon as a double


  • Name: minNum
      • Takes in two integer parameters
      • determines which of the two numbers is smaller
      • returns the smaller number


  • Name: notString
    • It takes in one string parameter
    • It returns a new string where "not " has been added to the front.
    • However, if the string already begins with "not", it return the string unchanged.




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 Eclipse 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 Canvas.
  • The output of your program should look identical to the sample output below (except user input will vary).

Activity 17.2: Into the Void (10 pts)

  • Void functions are useful for printing out information in a particular format.
  • Let's consider dates and times.
  • In America, we use the 12 hour clock, but in Europe, the 24 hour clock is used. For example, in America, 8:30 at night is represented as 8:30pm, while in Europe, it is represented as 20:30.
  • In America, we write dates in this format MM-DD-YYYY. In Europe, dates are often written as DD.MM.YYYY
  • Let's write a program that uses void functions to format dates and times.
  • We will print each date and time in both the American and European formats for our user.
  • Open up Eclipse and create a new C++ file named dateTime.cpp.
  • Copy and paste the starter code below into your file:
/*
* Name(s)
* Section info
*/
#include<iostream>
using namespace std;


//write functions here

int main() {
    int year;
    int day;
    int month;
    int hour;
    int minutes;
    string dayEve;

    cout << "Welcome! This program will print dates and times in both the American and European styles!\n\n";

    cout <<"First, let's print a formatted date.\n\n";
   
    cout << "Please enter the current year: ";
    cin >> year;
    cout << "Please enter the current month: ";
    cin >> month;
    cout << "Please enter the current day: ";
    cin >> day;
    cout << endl;
  
    //call to the formatDateAmerican function here
    //call to the formatDateEuropean function here
   
    cout << "\nNow, let's print a formatted time.\n\n";
   
    cout << "Please enter the current hour: ";
    cin >> hour;
    cout << "Please enter the current minutes: ";
    cin >> minutes;
    cout << "Please enter whether it is \"morning\" or \"evening\": ";
    cin >> dayEve;
    cout << endl;

   
    //call to the formatTimeAmerican function here
    //call to the formatTimeEuropean function here

    cout << "\nBye! See you another day!" << endl;

    return 0;
}



  • Now, you need to write four functions as follows:
formatDateAmerican
takes as input three integer parameter, one for the year, one for the month and one for the day
prints a formatted version of the date to the console, using the format m/d/yyyy
returns nothing
formatDateEuropean
takes as input three integer parameters, one for the year, one for the month and one for the day
prints a formatted version of the date to the console, using the format d.m.yyyy
returns nothing
formatTimeAmerican
takes as input two integer parameters, one for the hour, one for the minutes, and a string parameter that contains either "morning" or "evening"
prints a formatted version of the time to the console, using the format H:MMam or H:MMpm
returns nothing
formatTimeEuropean
takes as input two integer parameters, one for the hour, one for the minutes, and a string parameter that contains either "morning" or "evening"
prints a formatted version of the time to the console, using the 24 hour clock. Note that there is no am or pm in this format.
returns nothing

  • Upload your dateTime.cpp file to Canvas.

Your output should look identical the output below when you are finished:


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.3: Prototypes and Comments (10 pts)

  • In the text box under Activity 17.3 on Canvas, write the prototypes for the following functions.
  • Then below each prototype write a comment describing what the function does.
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 to Canvas.


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 feet, int inches, double weight);
//Calculates a user's Body Mass Index

int convertFeetInches(int feet, int inches);
//Converts height in feet and inches to height in inches

int squareInches(int inches);
//Squares the height in inches

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 feet, int inches, double weight) {
    int heightInches = convertFeetInches(feet,inches);
    int heightInches2 = squareInches(heightInches);
    double bmi = 703 * weight / heightInches2;
    return bmi;
}

int convertFeetInches(int feet, int inches) {
    return 12 * feet + inches;
}


int squareInches(int inches) {
    return inches * inches;
}


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

Upcoming Assignments

  • Assignment 17 due Wednesday on Canvas
  • Lab 9 due Friday at midnight on Canvas


~See You Wednesday!~