Slide 9.9: Looping (cont.)
Slide 9.11: User-defined functions (cont.)
Home

User-Defined Functions


The general format of a user-defined function is either one of the following:
  public   dataType funName( dataType arg, ... ) { ... }
  private  dataType funName( dataType arg, ... ) { ... }
public indicates that the function is applicable to the whole program and private indicates that the function is only applicable to a procedure.

This example shows how to create a user-defined function, which performs the interest calculation.

A user can calculate future value of a certain amount of money he/she has today based on the interest rate and the number of years from now.

01using System;
02using System.Windows.Forms;
03 
04namespace WindowsFormsApp3 {
05  public partial class Form1 : Form {
06    public Form1( ) { InitializeComponent( ); }
07 
08    private void Compute_Click( object sender, EventArgs e ) {
09      string presentval = PV.Text;
10      string interest   = rate.Text;
11      string period     = years.Text;
12      double futureVal  = FV( presentval, interest, period );
13      Microsoft.VisualBasic.Interaction.MsgBox(
14          "The future value is" + futureVal );
15    }
16 
17    public double FV( string PV, string i, string n ) {
18      double result;
19      result = 1 + double.Parse( i ) / 100;
20      result = Math.Pow( result, int.Parse( n ) );
21      result = double.Parse( PV ) * result;
22      return ( result );
23    }
24  }
25}