Delegating tasks with Functions

Table of Contents


c2_u09_Functions_image.png

1. Program Structure

z_errorinmain.png

As programs become more sophisticated and offer more features, the size of the program increases. At some point, it becomes too complicated to keep your entire program just within main().

(You could certainly do it, but maintaining it would be a nightmare!)

One of the tools we use to build modular, easier-to-read code is functions. By using functions, we can delegate tasks out to other portions of the program, passing inputs as data to the function, and receiving some kind of output as a result.

As a basic example, let's say we need to calculate square footage of a room in multiple places in a program. By making a float GetArea( float width, float length ) function.

Then, we only have to implement the formula once and can use the function in every part of the program. Then, we wouldn't be copy-and-pasting the same formula over and over again in the code - which also means less likelihood of errors, and easier to update later as needed.

Program flow and functions

Whenever a function is called, the program flow is redirected into that function, running from top-to-bottom as normal (with branching and loops changing that flow). Once the function has completed, it can return some data, which is received by the call location.

From a design standpoint, this means we can break out different parts of programs into their own sections. Each function has a name, which should be used to label what the purpose of its code is.

c2_u09_Functions_functioncall.png

c2_u09_Functions_programbreakout.png


2. 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

3. 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"; }

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

Author: Rachel Wil Sha Singh

Created: 2023-11-01 Wed 12:28

Validate