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.

 using System;
 using System.Windows.Forms;

 namespace WindowsFormsApp3 {
   public partial class Form1 : Form {
     public Form1( ) { InitializeComponent( ); }

     private void Compute_Click( object sender, EventArgs e ) {
       string presentval = PV.Text;
       string interest   = rate.Text;
       string period     = years.Text;
       double futureVal  = FV( presentval, interest, period );
       Microsoft.VisualBasic.Interaction.MsgBox(
           "The future value is" + futureVal );
     }

     public double FV( string PV, string i, string n ) {
       double result;
       result = 1 + double.Parse( i ) / 100;
       result = Math.Pow( result, int.Parse( n ) );
       result = double.Parse( PV ) * result;
       return ( result );
     }
   }
 }