Presentation is loading. Please wait.

Presentation is loading. Please wait.

3. User Defined Functions

Similar presentations


Presentation on theme: "3. User Defined Functions"— Presentation transcript:

1 3. User Defined Functions

2 Procedures and Functions
Both Procedures and Functions Group of statements Identified by unique name mirror real life activities Procedures – just do something Functions – return a value

3 Built in Functions: SQR
Sqr – gives square a number function Sqr(X: Extended): Extended; Examples Sqr(4) 16 Sqr(3) 9 Sqr(2) 4 X: Extended Sqr Extended

4 Built in Functions: Random
Random – generates random numbers function Random(): Extended; function Random(Limit: Integer): Integer; Random Extended Limit: integer Random integer

5 User Defined Functions
Syntax very similar to procedure definition: function <name>(<parameters>): <type>; begin ... Result := <value> end; Where <name> represents function’s name you choose <parameters> represent information needed <type> represents the return type <value> represent the return value

6 Exercise: code to diagram
Draw function diagram for the following code: function Thing(): double; function Miles(km: real): real; function Double(num: integer): integer;

7 Exercise: diagram to code
Generate the code for the following diagrams: Mins: integer Minutes integer Hours: integer Pounds: integer Euros integer

8 Example: Functions Demo (form)

9 Example: Functions Demo (code)
implementation ... const MinutesPerHour = 60; const KMperMile = 1.6; function Minutes(Mins: integer; Hours: integer): integer; begin Result := Mins + (Hours * MinutesPerHour); end; function Miles(km: real): real; Result := km / KMperMile; procedure TfrmFuncts.cmdMinutesClick(Sender: TObject); var tmpMins: integer; var tmpHours: integer; var resMins: integer; tmpMins := StrToInt(txtMins.Text); tmpHours := StrToInt(txtHours.Text); resMins := Minutes(tmpMins, tmpHours); lblMinutes.Caption := IntToStr(resMins); procedure TfrmFuncts.cmdMilesClick(Sender: TObject); var tmpKM: real; var resMiles: real; tmpKM := StrToFloat(txtKM.Text); resMiles := Miles(tmpKM); lblMiles.Caption := FloatToStr(resMiles); end.

10 Meet George Common Boa Constrictor (Boa Constrictor Constrictor).

11 George (cont.) Problem: Solution Difficult to keep
Require temperature and humidity controlled environment Much of the literature is from the US Temperature in Fahrenheit Solution Need a program to convert from Celsius to Fahrenheit

12 George (cont.) To convert from Fahrenheit to Celsius:
To convert from Celsius to Fahrenheit:

13 George (cont.) The code: function FtoC(F: double): double; begin
end;


Download ppt "3. User Defined Functions"

Similar presentations


Ads by Google