User-Defined Functions

Many computer programming languages provide the facility for a programmer to define and create their own functions. This facility is vital in creating modular programs and allows programmers to refine and add to existing functions in order to create purpose built software.

The example program shown below contains four user-defined functions. Each function is named following a verb/noun convention and each function (module) is designed to carry out a specific task.

Input – GetNumbers ( )
Process – CalcTotal ( ) and CalcAverage ( )
Output – DispAnswers ( )

<html>
<head>

<script type='text/javascript'>
var Number1 = 0 ;
var Number2 = 0 ;
var Total = 0 ;
var Average = 0 ;

function GetNumbers ()
{ // begin GetNumbers

Number1 = prompt ('Enter first number: ') ;
Number1 = parseInt (Number1) ;
Number2 = prompt ('Enter second number: ') ;
Number2 = parseInt (Number2) ;

} // end GetNumbers

function CalcTotal ()
{ // begin CalcTotal

Total = Number1 + Number2 ;

} // end CalcTotal

function CalcAverage ()
{ // begin CalcAverage

Average = Total / 2 ;

} // end CalcAverage

function DispAnswers ()
{ // begin DispAnswers

alert ('Total = ' + Total + '\n' + 'Average = ' + Average) ;

} // end DispAnswers

// Main Program
GetNumbers () ;
CalcTotal () ;
CalcAverage () ;
DispAnswers () ;

</script>
</head>
<body>
</body>
</html>

Next: Parameter Passing