140 likes | 335 Views
3. User Defined Functions. 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. Built in Functions: SQR. Sqr – gives square a number
E N D
Procedures and Functions • Both Procedures and Functions • Group of statements • Identified by uniquename • mirror real life activities • Procedures – just do something • Functions – return a value
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
Built in Functions: Random • Random – generates random numbers function Random(): Extended; function Random(Limit: Integer): Integer; Random Extended Limit: integer Random integer
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
Exercise: code to diagram • Draw function diagram for the following code: function Thing(): double; function Miles(km: real): real; function Double(num: integer): integer;
Exercise: diagram to code • Generate the code for the following diagrams: Mins: integer Minutes integer Hours: integer Pounds: integer Euros integer
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; begin Result := km / KMperMile; end; procedure TfrmFuncts.cmdMinutesClick(Sender: TObject); var tmpMins: integer; var tmpHours: integer; var resMins: integer; begin tmpMins := StrToInt(txtMins.Text); tmpHours := StrToInt(txtHours.Text); resMins := Minutes(tmpMins, tmpHours); lblMinutes.Caption := IntToStr(resMins); end; procedure TfrmFuncts.cmdMilesClick(Sender: TObject); var tmpKM: real; var resMiles: real; begin tmpKM := StrToFloat(txtKM.Text); resMiles := Miles(tmpKM); lblMiles.Caption := FloatToStr(resMiles); end; end.
Meet George • Common Boa Constrictor (Boa Constrictor Constrictor).
George (cont.) • Problem: • 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
George (cont.) • To convert from Fahrenheit to Celsius: • To convert from Celsius to Fahrenheit:
George (cont.) • The code: function FtoC(F: double): double; begin FtoC := ((f-32) * 5) / 9; end;