Programming Fundamentals/Function Examples

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Overview[edit | edit source]

The following pseudocode and flowchart examples take the Temperature program from the previous chapter and separate the functionality into independent functions for input, processing, and output, as GetFahrenheit, CalculateCelsius, and DisplayResult, respectively.

Discussion[edit | edit source]

As independent functions, each function acts as a miniature program, with its own input, processing, and output. As you review the following code, note which functions have parameters (input) and which functions have return values (output). Parameters and return values will be discussed in the next few pages.

Function Purpose Parameters (input) Return Value (output)
Main main program none none
GetFahrenheit input none fahrenheit
CalculateCelsius processing fahrenheit celsius
DisplayResult output fahrenheit, celsius none

Pseudocode[edit | edit source]

Function Main
    ... This program asks the user for a Fahrenheit temperature, 
    ... converts the given temperature to Celsius,
    ... and displays the results.

    Declare Real fahrenheit
    Declare Real celsius
    Assign fahrenheit = GetFahrenheit()
    Assign celsius = CalculateCelsius(fahrenheit)
    Call DisplayResult(fahrenheit, celsius)

Function GetFahrenheit
    Declare Real fahrenheit
    Output "Enter Fahrenheit temperature:"
    Input fahrenheit
Return Real fahrenheit

Function CalculateCelsius (Real fahrenheit)
    Declare Real celsius
    Assign celsius = (fahrenheit - 32) * 5 / 9
Return Real celsius

Function DisplayResult (Real fahrenheit, Real celsius)
    Output fahrenheit & "° Fahrenheit is " & celsius & "° Celsius"

Output[edit | edit source]

Enter Fahrenheit temperature:
100° Fahrenheit is 37.7777777777778° Celsius

Flowchart[edit | edit source]

Main function flowchart GetFahrenheit function flowchart CalculateCelsius function flowchart DisplayResult function flowchart

References[edit | edit source]