Programming Fundamentals/Function Examples

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

Overview[edit]

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]

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]

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)
End

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"
End

Output[edit]

Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7777777777778° Celsius

Flowchart[edit]

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

References[edit]