CS 134 Unit 09: Calling functions

Table of Contents


Create your own source code files in your replit project. Remember to use the correct file extension:

File extension Language Run command
.py Python python3 FILENAME.py
.cpp C++ g++ FILENAME.cpp -o program1 && ./program1.out

This will all be one program, but building up on each other, so at the end you should only have one file in the project.

As you're working on the program, make sure to try to build (for C++) and run regularly! It's easier to fix syntax errors if you catch them early! I care much more about working code, even if it's incomplete. I do not care for "complete" code that doesn't actually run.


1. Introduction: About functions

1.1. Function basics

When we define a function, there are three main pieces of information:

  1. What inputs does it take?
  2. What output does it return?
  3. What is the name of the function?

For example…

Inputs Outputs Function name
number1, number2 sum of number1 and number2 Sum
number1, number2 whichever number is bigger Max

We can write functions that take input or not, and we can write them to return output or not. Basically:

Input Output
yes yes
yes no
no yes
no no

1.2. Defining a function

When we define a function it needs to happen before the program code. This usually means at the top of the file, or in C++, before main().

A function definition takes this form:

Python

def FUNCTIONNAME( INPUT1, INPUT2 ):
    # Function code goes here

C++

RETURNTYPE FUNCTIONNAME( INPUT1TYPE INPUT1NAME, INPUT2TYPE INPUT2 NAME )
{
  // Function code goes here
}
Input Output Example function (Python) Example function (C++)
yes yes def Sum( a, b ): return a + b float Sum( float a, float b ) { return a + b; }
yes no def Display( text ): print( text ) void Display( string text ) { cout << text; }
no yes def GetTax(): return 0.091 float GetTax() { return 0.091; }
no no def DisplayMenu(): print( "1. Save, 2. Load" ) void DisplayMenu() { cout << "1. Save, 2. Load"; }

1.3. Calling a function

When we call a function, we do so from the main program code (for now, while we're writing simple programs :). A function call requires that we use the function name, pass in any required inputs, and store the function's output in a variable.

Input Output Example function (Python) Example function (C++)
yes yes result = Sum( 1, 2 ) float result = Sum( 1, 2 );
yes no Display( "Hello!" ) Display( "Hello!" );
no yes tax = GetTax() float tax = GetTax();
no no DisplayMenu() DisplayMenu();

If a function returns output, that always must be stored in a variable.

If a function requries input, we can either pass in literal values (hard coded numbers or strings) or pass in variables.

Python

num1 = float( input( "Enter number 1: " ) )
num2 = float( input( "Enter number 2: " ) )
result = Sum( num1, num2 );
print( "Result:", result );

C++

int main()
{
  float num1, num2, result;

  cout << "Enter number 1: ";
  cin >> num1;

  cout << "Enter number 2: ";
  cin >> num2;

  result = Sum( num1, num2 );
  cout << "Result: " << result << endl;

  return 0;
}

2. Programming assignments

2.1. Program 1: No In, No Out

Starter code:

Python:

# Function definition
def RecommendedBook():
  print( "Favorite book: XYZ" )
  # Function end




# PROGRAM CODE

# Function call
RecommendedBook()

C++

#include <iostream>
using namespace std;

// Function definition
void RecommendedBook()
{
  cout << "Favorite book: XYZ" << endl;
}

int main()
{
  // Function call
  RecommendedBook();

  return 0;
}

Instructions:

Update the text inside the RecommendedBook function so that it says your favorite book. The function is already being called by the program, so there's nothing else to update.

Example output:

Favorite book: Masters of Doom

2.2. Program 2: Yes In, No Out

Starter code:

Python:

# DEFINE A FUNCTION
def DisplayFraction( numerator, denominator ):
  print( str( numerator ) + "/" + str( denominator ) )
  # End of function



# PROGRAM CODE


num = 0
denom = 0

# Ask the user to enter a numerator (int). Store in a variable named `num`.

# Ask the user to enter a denominator (int). Store in a variable named `denom`.

# Call the DisplayFraction function, passing in `num` and `denom`.
DisplayFraction( num, denom )

C++

#include <iostream>
using namespace std;

// Function definition
void DisplayFraction( int numerator, int denominator )
{
  cout << numerator << "/" << denominator;
}


int main()
{
  int num, denom;

  // PROGRAM CODE
  // Ask the user to enter a numerator (int). Store in a variable named `num`.

  // Ask the user to enter a denominator (int). Store in a variable named `denom`.

  // Call the DisplayFraction function, passing in `num` and `denom`.
  DisplayFraction( num, denom );
}

Instructions: Under the section marked // PROGRAM CODE, do the following:

  1. Integer variables num and denom have already been declared.
  2. Ask the user to enter a numerator, store their input as an integer in the num variable.
  3. Ask the user to enter a denominator, store their input as an integer in the denom variable.
  4. A call to the DisplayFraction function is already written. It is receiving num and denom as inputs.

Example output:

Enter a numerator: 1
Enter a denominator: 2
Fraction: 1/2

2.3. Program 3: No In, Yes Out

Starter code:

Python:

# Function definition
def GetAddress():
  return "12345 College Blvd, Overland Park, KS 66210";
# end of function


# PROGRAM CODE
# Create a string variable named `college_address`.
college_address = ""

# Call the GetAddress function and assign its return result to this variable.

# Display "The college's address is:"

# Display the `college_address` variable.

C++

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

// Function definition
string GetAddress()
{
  return "12345 College Blvd, Overland Park, KS 66210";
}


int main()
{
  // PROGRAM CODE
  // Create a string variable named `college_address`.
  string college_address;

  // Call the GetAddress function and assign its return result to this variable.

  // Display "The college's address is:"

  // Display the `college_address` variable.
}

Instructions: Under the section marked // PROGRAM CODE, do the following:

  1. A string variable college_address has already been declared.
  2. Call the GetAddress function, storing the output in the college_address variable.
    • variable = FUNCTIONNAME()
    • (In C++, put a semicolon at the end!)
  3. Display "The college's address is:", and the value of the college_address variable.

Example output:

The college's address is:
12345 College Blvd, Overland Park, KS 66210

2.4. Program 4: Yes In, Yes Out

Starter code:

Python:

# Function definition
def GetAverage( num1, num2, num3 ):
  return (num1+num2+num3)/3
# End of function


# PROGRAM CODE
number1 = 0
number2 = 0
number3 = 0
average = 0

# Ask the user to enter a first number, store in `number1`.

# Ask the user to enter a second number, store in `number2`.

# Ask the user to enter a third number, store in `number3`.

# Call the GetAverage function, passing in `number1`, `number2`, and `number3`. Store the returned result in the `average` variable.

# Display the "The average is:" and then the `average` variable.

C++

#include <iostream>
using namespace std;

// Function definition
float GetAverage( float num1, float num2, float num3 )
{
  return (num1+num2+num3)/3;
}

int main()
{
  // PROGRAM CODE
  float number1, number2, number3, average;
  // Ask the user to enter a first number, store in `number1`.

  // Ask the user to enter a second number, store in `number2`.

  // Ask the user to enter a third number, store in `number3`.

  // Call the GetAverage function, passing in `number1`, `number2`, and `number3`. Store the returned result in the `average` variable.

  // Display the "The average is:" and then the `average` variable.
}

Instructions: Under the section marked // PROGRAM CODE, do the following:

  1. Four variables have already been declared: number1, number2, number3, and average.
  2. Ask the user to enter a value for number1, store their response as a float.
  3. Ask the user to enter a value for number2, store their response as a float.
  4. Ask the user to enter a value for number3, store their response as a float.
  5. Call the GetAverage function, passing in number1, number2, and number3 as the inputs, and storing the output to the average variable.
    • variable = FUNCTIONNAME( INPUT1, INPUT2, INPUT3 )
    • (With C++, end that line with a semicolon!)
  6. Display "The average is:", then display the value of the average variable.

Example output:

Enter number1: 4.0
Enter number2: 4.5
Enter number3: 5.0
The average is: 4.5

Author: Rachel Wil Sha Singh

Created: 2023-11-01 Wed 12:28

Validate