A function that converts temperatures
Write to_fahrenheit(c) once and use it for Kathmandu, Jumla and Biratnagar. Change each town's temperature, watch every call get its own c, and see one rule give three answers.
Core concept
A function keeps a rule in one place: to_fahrenheit(c) returns c × 9 ÷ 5 + 32, and every call gives it a new argument for its parameter c
Topic: Functions and recursion
Nepal measures temperature in degrees Celsius (°C), but some countries use degrees Fahrenheit (°F). Water freezes at 0 °C, which is 32 °F, and boils at 100 °C, which is 212 °F. The rule is: multiply by 9, divide by 5 and add 32. Instead of writing that rule for every town, a program puts it in a function: FUNCTION to_fahrenheit(c) RETURN c * 9 / 5 + 32. Each call gives the function a new value for its parameter c, such as Kathmandu's temperature, and the function returns that town's temperature in °F. The rule is written once and used three times.
What you will learn
- Write a function with one parameter and a return value.
- Trace calls of one function with different arguments.
- Explain why keeping a rule in one function helps.
- Spot and fix a mistake in a function's rule.
Before you start
- Know how variables and functions are called (Functions: a machine for areas).
Materials
- A weather report from the newspaper or radio
Equipment
- None
Procedure
- Run the program and read the three temperatures in °F.
- Make Jumla freeze at 0 °C and step through the calls.
- Find the temperature that makes Biratnagar 104 °F.
- Answer the practice challenges.