1 Procedures Blocks of code which can be called from anywhere in a program Enable us to avoid needless repetition of the same code Can take parameters.

Slides:



Advertisements
Similar presentations
Spring Semester 2013 Lecture 5
Advertisements

Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
VBA Modules, Functions, Variables, and Constants
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 10: 1 TEST!!
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Creating Packages. 2 home back first prev next last What Will I Learn? Describe the reasons for using a package Describe the two components of a package:
Introduction to Python
Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs.
The switch StatementtMyn1 The switch Statement Sometimes there can be a multiple-choice situation, in which you need to execute a particular set of statements.
Apply Sub Procedures/Methods and User Defined Functions
SE-1010 Dr. Mark L. Hornick 1 Defining Your Own Classes Part 3.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Procedures and Functions Computing Module 1. What is modular programming? Most programs written for companies will have thousands of lines of code. Most.
COMPUTER PROGRAMMING. Functions What is a function? A function is a group of statements that is executed when it is called from some point of the program.
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
Fundamental Programming: Fundamental Programming Introduction to C++
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Procedural programming in Java Methods, parameters and return values.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Chapter 7 Functions. Types of Functions Value returning Functions that return a value through the use of a return statement They allow statements such.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
BMTRY 789 Lecture 10: SAS MACRO Facility Annie N. Simpson, MSc.
ProgLan Python Session 4. Functions are a convenient way to divide your code into useful blocks, allowing us to: order our code, make it more readable,
JavaScript, Fourth Edition
C++ / G4MICE Course Session 2 Basic C++ types. Control and Looping Functions in C Function/method signatures and scope.
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
CSE 1301 Lecture 6 Writing Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
1 Structure of a C Program (continued) Presentation original from Dr. Turner’s class USF - COP C for Engineers Summer 2008.
CREATING STORED PROCEDURES AND FUNCTIONS. Objectives After completing this lecture, you should be able to do the following: Differentiate between anonymous.
CSI 3125, Subprograms, page 1 Subprograms General concepts Parameter passing Functions Subprograms as parameters.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Passing Parameters. 2 home back first prev next last What Will I Learn? List the types of parameter modes Create a procedure that passes parameters Identify.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Object Oriented Programming(Objects& Class) Classes are an expanded concept of data structures: like.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
External Scope CECS 277 Mimi Opkins.
More about comments Review Single Line Comments The # sign is for comments. A comment is a line of text that Python won’t try to run as code. Its just.
Section 2.1: Programming paradigms
User-Written Functions
Object-Oriented Programming: Classes and Objects
COMP 170 – Introduction to Object Oriented Programming
Spreadsheet-Based Decision Support Systems
Functions and Procedures
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
Section 2.1: Programming paradigms
Object-Oriented Programming: Classes and Objects
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Class Structure 16-Nov-18.
OOP Paradigms There are four main aspects of Object-Orientated Programming Inheritance Polymorphism Abstraction Encapsulation We’ve seen Encapsulation.
Functions and Procedures
Class Structure 7-Dec-18.
Chapter 4 Writing Classes.
Class Structure 2-Jan-19.
Workshop for Programming And Systems Management Teachers
Class Structure 25-Feb-19.
Methods.
Chapter (3) - Procedures
Subprograms General concepts Parameter passing Functions
Corresponds with Chapter 5
Presentation transcript:

1 Procedures Blocks of code which can be called from anywhere in a program Enable us to avoid needless repetition of the same code Can take parameters Ordinary (‘Value’) Parameters ‘Variable’ Parameters Procedures must be defined before they are used

2 Simple Example - Anonymous Declared in the implementation section, immediately after { $R *.DFM} Declared in the implementation section, immediately after { $R *.DFM} Call

3 private Information; public End; Implementation {$R *.DFM} Procedure TForm1.Information; Begin MessageDlg(‘Hello World!’, mtInformation, [mbOK], 0); End; Procedure TForm1GoBtnClick(Sender: Tobject); Begin Information; End; Simple Example - method Declared in the interface section, as either private or public Declared in the interface section, as either private or public Call Preceeded by object name

4 Making it more flexible The example procedure encapsulates an Information dialog, and might be particularly useful if we needed to call it several times in a program However, it’s not very useful Unless ‘Hello, World!’ is the only message we ever want to display! We can give it a parameter the message we want to display

5 Example (2) procedure Information(msg: String); begin MessageDlg(msg, mtInformation, [mbOK], 0); end; procedure Information(msg: String); begin MessageDlg(msg, mtInformation, [mbOK], 0); end; Why is the parameter not called message? It’s a KEYWORD (Reserved Word) We can’t use its name for a variable Such words are displayed by Delphi in bold How do we call it? procedure TForm1.GoBtnClick(Sender: TObject); begin Information('Your Message Here'); end; procedure TForm1.GoBtnClick(Sender: TObject); begin Information('Your Message Here'); end;

6 Parameters We wouldn’t expect to be limited to only one parameter And we’re not But we must declare the names and types of all parameters Procedure Declaration Syntax procedure name(param1, param2: Type1; param3: Type2); {optional local declarations} begin {statements go here} end; procedure name(param1, param2: Type1; param3: Type2); {optional local declarations} begin {statements go here} end;

7 Parameter Declarations Generally, parameters are declared by giving their name, then a colon (:) and then their type Individual parameters are separated by semicolons (;) If there are several adjacent parameters of the same type, we can save ourselves some typing by separating their names with commas, and only putting the colon followed by the type after the last of them

8 Calling a Procedure We call a procedure simply by using its name (see Information above) If there are parameters they must be listed between ( … ) following the name If more than one parameter (of whatever type) they are separated by commas Not semicolons!

9 Calling a Procedure procedure MyProc(param1: Integer; param2: String); begin ShowMessage(param2 + IntToStr(param1)); end; procedure MyProc(param1: Integer; param2: String); begin ShowMessage(param2 + IntToStr(param1)); end; MyProc(5, ‘Value’); Parameters are matched by position. The procedure gets a COPY of each value when it is called. Types of actual parameters must MATCH those of the formal parameters (normally, be the same type) Formal Parameters Actual Parameters

10 Local Declarations We can declare variables locally in procedures using the var statement, in the way we’ve already seen The parameters are automatically declared — we should NOT declare these locally ourselves Variables declared locally inside a procedure are visible only inside that procedure procedure MyProc(param1: SomeType); var myVariable: AnotherType; begin // some code end; procedure MyProc(param1: SomeType); var myVariable: AnotherType; begin // some code end;

11 Variable Parameters Ordinarily, a procedure gets a COPY of the values passed to it Any changes we make to the value inside the procedure only apply to the copy NOT to the original variable (if one was used)

12 Example procedure TestParams(x, y: Integer; log: TMemo); begin log.Lines.Add(Format('Entering procedure: x = %d y = %d', [x,y])); x := x + 10; y := y * 3; log.Lines.Add(Format('Leaving procedure : x = %d y = %d', [x,y])); end; procedure TForm1.GoBtnClick(Sender: TObject); var x, y : Integer; begin x := 5; y := 9; Memo1.Lines.Add(Format('Calling procedure : x = %d y = %d', [x,y])); TestParams(x, y, Memo1); Memo1.Lines.Add(Format('After procedure : x = %d y = %d', [x,y])); end; procedure TestParams(x, y: Integer; log: TMemo); begin log.Lines.Add(Format('Entering procedure: x = %d y = %d', [x,y])); x := x + 10; y := y * 3; log.Lines.Add(Format('Leaving procedure : x = %d y = %d', [x,y])); end; procedure TForm1.GoBtnClick(Sender: TObject); var x, y : Integer; begin x := 5; y := 9; Memo1.Lines.Add(Format('Calling procedure : x = %d y = %d', [x,y])); TestParams(x, y, Memo1); Memo1.Lines.Add(Format('After procedure : x = %d y = %d', [x,y])); end; The procedure can’t get at the memo directly so we must pass it as a parameter

13 Result

14 Variable Parameters Often we WANT a change to a parameter to affect the program outside of the procedure ‘Variable Parameters’ — often called ‘var parameters’ — let us do this But do not overuse

15 Example procedure TestParams(var x, y: Integer; log: TMemo); begin log.Lines.Add(Format('Entering procedure: x = %d y = %d', [x,y])); x := x + 10; y := y * 3; log.Lines.Add(Format('Leaving procedure : x = %d y = %d', [x,y])); end; procedure TForm1.GoBtnClick(Sender: TObject); var x, y : Integer; begin x := 5; y := 9; Memo1.Lines.Add(Format('Calling procedure : x = %d y = %d', [x,y])); TestParams(x, y, Memo1); Memo1.Lines.Add(Format('After procedure : x = %d y = %d', [x,y])); end; procedure TestParams(var x, y: Integer; log: TMemo); begin log.Lines.Add(Format('Entering procedure: x = %d y = %d', [x,y])); x := x + 10; y := y * 3; log.Lines.Add(Format('Leaving procedure : x = %d y = %d', [x,y])); end; procedure TForm1.GoBtnClick(Sender: TObject); var x, y : Integer; begin x := 5; y := 9; Memo1.Lines.Add(Format('Calling procedure : x = %d y = %d', [x,y])); TestParams(x, y, Memo1); Memo1.Lines.Add(Format('After procedure : x = %d y = %d', [x,y])); end;

16 Result

17 Important Note We said earlier that the types of the formal and actual parameters must MATCH For ordinary (‘value’) parameters, this means that the actual parameter must be: a variable of the same type an expression of a matching type a value of a matching type In practice, ‘matching type’ means either the same type or an Integer if the formal parameter is of type Real For variable (‘var’) parameters, the actual parameter MUST BE A VARIABLE OF THE SAME TYPE

18 Functions Declaration and Use

19 Functions A function, like a procedure, is a block of code The difference is that it returns a value to where it is called from Format (see above) is a function So are mathematical functions: Sin Cos Log …

20 Function Example function Average(data: TStrings): Real; var i: Integer; sum, count: Integer; begin sum := 0; count := 0; for i := 0 to data.Count -1 do begin sum := sum + StrToInt(data[i]); count := count + 1; end; result := sum/count; end; procedure TForm1.AvgBtnClick(Sender: TObject); var res : Real; begin res := Average(Memo1.Lines); ResultLbl.Caption := FloatToStr(res); end; function Average(data: TStrings): Real; var i: Integer; sum, count: Integer; begin sum := 0; count := 0; for i := 0 to data.Count -1 do begin sum := sum + StrToInt(data[i]); count := count + 1; end; result := sum/count; end; procedure TForm1.AvgBtnClick(Sender: TObject); var res : Real; begin res := Average(Memo1.Lines); ResultLbl.Caption := FloatToStr(res); end; used in an expression

21 Function Example

22 Notes We specify the RETURN TYPE of the function after the parameter list and following a colon (:) We use the word function in the declaration instead of procedure We should NOT write a function which uses var parameters The value which the function will return is assigned to the special variable result Notice that result is not shown in bold in Delphi => It isn’t reserved So need to take care not to declare a variable with this name!

23 Summary Procedures and functions useful for code which is needed repeatedly Save us typing Also make program easier to read Like making new commands Parameters Make procedures and functions more flexible Variable parameters Functions return a result Used in an expression Special variable, result (NOT reserved!)