Skip to content
Programming Functions and recursion
All classes Intermediate About 15 min Premium

Functions: a machine for areas

Define a function area(length, breadth) once and call it for a kitchen, a hall and a bedroom. Watch each call open a new frame with its own parameters, see the value it returns, and change the bedroom's size to reach a target area.

Core concept

A function is a named set of steps written once and used many times: its parameters receive the arguments of each call, and return sends its answer back to where it was called

Topic: Functions and recursion

When you need the same calculation many times, you do not want to write it again and again. A function is a small machine with a name. You write its steps once: FUNCTION area(length, breadth) … RETURN length * breadth. Then you call it whenever you need it: area(4, 3). The values in the call, 4 and 3, are the arguments; inside the function they arrive in its parameters, length and breadth. The function works with its own variable: A named box that holds a value the program can read and change. All key words, gives its answer back with RETURN, and the program carries on where it called it. If the rule ever changes, you fix it in one place, and every call uses the new rule.

Key words explained

What you will learn

  • Explain what a function, a parameter, an argument and a return value are.
  • Trace a call: arguments go into the parameters, and the returned value comes back.
  • Use one function for several different inputs.
  • Write the lines of a function and a call in order.

Before you start

  • Know how variables and assignment work.

Materials

  • A notebook and a floor plan of a home

Equipment

  • None

Procedure

  1. Run the program and read the three areas and the total.
  2. Step through it and watch each call open a frame on the call stack.
  3. Change the bedroom's length and width and run it again.
  4. Answer the practice challenges.
Premium experiment Create a free account