Welcome to Lesson 15! Learning Objectives By the end of today's class, you should know...
Announcements
Review ActivityWith a partner, answer the following questions. Note that these are the types of questions I will ask you on your midterm!
string BB= "Basketball";
double height; cout << "Please enter your height in inches: "; cin >> height; while (???????????????) { cin.clear(); ?????? cout << "Please enter numbers not words.\n"; cout << "Please enter your height in inches: "; cin >> height; } Strings ContinuedThe Problem with Newlines
Example Using |
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()
andmain()
- 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
andnum2
are copied to the parametersa
andb
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
- A function definition has parameters
- 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
statementreturn result;
- For instance, our example function
add()
has a return statementint 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 15.2 Writing a Function (10 pts)
In this exercise we define our own function.
Specifications
- Copy the following program into a text editor, 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; }
- Write the signature for a function named
sub
that receives twoint
numbers and returns anint
value, like we did for theadd()
functionreturnType sub(two_int_parameters)
- Add the curly braces for the function body:
{ }
. - 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;
- Compile and run your code. What do you see when you compile? (click here)
- 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.
- Compile and run your modified program and verify the output looks like:
Enter two numbers to subtract: 3 1 Difference=2
- Save your sub.cpp file and submit it to Catalyst.
Completed Program
When finished, your application should look like the following.
Function Analogies
- Functions as a black box.

- Functions as a blue print.
- Functions as outsourcing or multiple departments within a company.
- Functions as a juicer.
Wrap Up
- With a partner, answer the questions from today's learning objectives
Upcoming Assignments- Assignment 15 due Tuesday at 3:20pm on Catalyst
- Midterm 2 next class
- Lab 7 due Friday at midnight
- With a partner, answer the questions from today's learning objectives
- Assignment 15 due Tuesday at 3:20pm on Catalyst
- Midterm 2 next class
- Lab 7 due Friday at midnight