Software Development Sub Procedures, Functions and Parameters.

Slides:



Advertisements
Similar presentations
Software development process. Explanation of the iterative nature of the software development process.
Advertisements

Modular Programming With Functions
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Modular Programming Splitting your program into functions and procedures.
Standard Algorithms. 4 Standard Algorithms Input Validation Finding the Maximum / Minimum Counting Occurrences Linear Search.
Shawlands Academy Computing Department Higher Computing Easter Study Class.
An Introduction to Programming with C++ Fifth Edition
VBA Modules, Functions, Variables, and Constants
CS 201 Functions Debzani Deb.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6: Functions.
The Project AH Computing. Functional Requirements  What the product must do!  Examples attractive welcome screen all options available as clickable.
Functions. Program complexity the more complicated our programs get, the more difficult they are to develop and debug. It is easier to write short algorithms.
Python quick start guide
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
C++ for Engineers and Scientists Third Edition
A Level Computing#BristolMet Session ObjectivesU2#S10 MUST describe the difference between constants, local and global variables SHOULD explain why constants.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
06/10/ Working with Data. 206/10/2015 Learning Objectives Explain the circumstances when the following might be useful: Disabling buttons and.
Procedures and Functions Computing Module 1. What is modular programming? Most programs written for companies will have thousands of lines of code. Most.
Input, Output, and Processing
3 - Variables Lingma Acheson Department of Computer and Information Science, IUPUI CSCI N331 VB.NET Programming.
I Power Int 2 Computing Software Development High Level Language Constructs.
C++ Programming Language Lecture 2 Problem Analysis and Solution Representation By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Software Development Topic 3 High Level Language Constructs.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Higher Grade Computing Studies 3. High Level Language Constructs Higher Computing Software Development S. McCrossan 1 Simple Data Types Integer: An integer.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
I Power Higher Computing Software Development High Level Language Constructs.
Practical Programming COMP153-08S Week 5 Lecture 1: Screen Design Subroutines and Functions.
First Steps in Modularization. Simple Program Design, Fourth Edition Chapter 8 2 Objectives In this chapter you will be able to: Introduce modularization.
‘Tirgul’ # 2 Enterprise Development Using Visual Basic 6.0 Autumn 2002 Tirgul #2.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
Top-down approach / Stepwise Refinement & Procedures & Functions.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Advanced Higher Computing Science Stacks Queues and linked lists.
Modularity using Functions Chapter 4. Modularity In programming blocks of code often can be "called up" and reused whenever necessary, for example code.
1 Writing Software Kashef Mughal. 2 Algorithms  The term algorithm (pronounced AL-go-rith-um) is a procedure or formula for solving a problem.  An Algorithm.
The Hashemite University Computer Engineering Department
Shawlands Academy Computing Department Higher Computing Easter Study Class.
Programming Constructs Notes Software Design & Development: Computational Constructs, Data Types & Structures, Algorithm Specification.
Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Higher Computing Science Answering programming questions in the exam.
Higher Computing Science
Unit 2 Technology Systems
Chapter 9: Value-Returning Functions
Topics Designing a Program Input, Processing, and Output
COMPUTATIONAL CONSTRUCTS
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
User-Defined Functions
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
Software development process
10.2 Procedures Passing Parameters 30/08/2019.
Presentation transcript:

Software Development Sub Procedures, Functions and Parameters

Local Variables A Local variable only has scope within the sub- procedure where it has been defined. PROCEDURE Looper() FOR counter FROM 1 TO 10 SEND counter TO DISPLAY END FOR END PROCEDURE

Why use local variables? Local variables mean that they only have a value inside sub-procedure they are declared in. Using local variables means that sub- procedures are “self contained” and can be reused without affecting the value of variables elsewhere in the program

Why use local variables? You can use the same variable name again in a different sub-procedure The memory used by a local variable is freed up when its sub-procedure has finished running

Global Variables Global variables are variables which have scope throughout a program. Any change to the value of a global variable within a sub-procedure will change its value anywhere else it occurs in the program.

Global Variables Global variables are best avoided as they make your procedures and functions less portable and your code less maintainable

A procedure without Parameters This Sub-Procedure can only perform one task PROCEDURE Eight_stars() FOR counter FROM 1 TO 8 # Local variable SEND " * " TO DISPLAY END FOR END PROCEDURE

A sub procedure with a value Parameter This sub-procedure is more flexible as it can be called with any value PROCEDURE Stars (number_of _stars) FOR counter FROM 1 TO number_of_stars SEND " * " TO DISPLAY END FOR END PROCEDURE

Calling the sub procedure SEND " How many stars?" TO DISPLAY RECEIVE number_of _stars (INTEGER) FROM KEYBOARD Stars (number_of _stars) PROCEDURE Stars (number_of _stars) FOR counter FROM 1 TO number_of_stars SEND " * " TO DISPLAY END FOR END PROCEDURE If the input to the question “How many stars” was 10 then the result would be: * * * * * * * * * *

Parameters Formal Parameters are variables which are declared when a sub-procedure or function is defined Actual parameters are used when a sub- procedure or function is called

Functions

How a function differs from a procedure A function returns a value A procedure performs a sequence of actions Function names and usually nouns Functions return a value so need to be declared as being a particular data type Procedure names are usually verbs

Built in mathematical functions int() sqr() abs()

Using mathematical functions SET value TO -56 SET newValue TO abs(value) SEND newValue TO DISPLAY Result would be 56

Using mathematical functions SET value TO 4 SET newValue TO sqr(value) SEND newValue TO DISPLAY Result would be 2

Using mathematical functions SET value TO 3.4 SET newValue TO int(value) SEND newValue TO DISPLAY Result would be 3

Built in string functions Left$() Right$() Len() Mid$()

Using String Functions SET myString TO "banana" SET newString TO left$(myString, 2) SEND newString TO DISPLAY Result would be ba

Using String Functions SET myString TO "banana" SET newString TO right$(string, 2) SEND newString TO DISPLAY Result would be na

Using String Functions SET myString TO "banana" SET newString TO mid$(string, 2, 3) SEND newString TO DISPLAY Result would be nan

Validnumber function FUNCTION ValidInteger()RETURNS INTEGER RECEIVE userInput FROM (INTEGER) KEYBOARD WHILE userInput 100 DO SEND "Input must be between 1 and 10 TO DISPLAY RECEIVE userInput FROM (INTEGER) KEYBOARD END WHILE RETURN userInput END FUNCTION

Validnumber function We would call this function within a program: SET number TO ValidInteger To give the variable number a value between 1 and 100

Validnumber function with value parameters FUNCTION ValidInteger(lowerLimit, upperLimit)RETURNS INTEGER RECEIVE userInput FROM (INTEGER) KEYBOARD WHILE userInput upperLimit DO SEND "Input must be between "& lowerLimit " and " &upperLimit" TO DISPLAY RECEIVE userInput FROM (INTEGER) KEYBOARD END WHILE RETURN userInput END FUNCTION

Input Validation (Function) We could call this function with actual parameters, 1 and 50 to return a number between 1 and 50: SET numberToUse TO ValidInteger(1,50) or we could call it with the actual parameters 1 and inputRange which is a variable which has a value assigned elsewhere in the program: RECEIVE inputRange FROM (INTEGER) KEYBOARD SET numberToUse TO ValidInteger(1,inputRange) This call would return a value between 1 and inputRange.

Why user defined functions? Functions return a value Functions make code more readable Functions, like procedures can be reused so make programming more efficient

Value Parameters A value parameter is one which is passed into a sub procedure or function and whose value is used by that procedure When a sub procedure is called with a variable as a value parameter, a copy of that variable is made using its formal parameter while the procedure is running. The copy of the variable is destroyed when the procedure has completed, so the memory can be reused

Reference Parameters When a sub procedure is declared with a reference parameter then when it is called with an actual variable its value is changed by that sub procedure. When a variable is passed as a reference parameter, the reference is to the memory location of the variable itself. No copy is being made.

Reference Parameters The value of the variable changes as a result of calling the sub procedure with it as a parameter PROCEDURE swap (REF a, REF b) SET temp TO a SET a TO b SET b TO temp END PROCEDURE

Reference Parameters Write a program which asks for two values (stored in the variables a and b) prints their values, then swaps the contents of the variables around and prints the new values

Reference Parameters PROCEDURE Get_values() RECEIVE a (INTEGER) FROM KEYBOARD RECEIVE b (INTEGER) FROM KEYBOARD End Sub PROCEDURE SwapValues() SEND "The value of a is " & a TO DISPLAY SEND "The value of b is " & b TO DISPLAY swap (a, b) SEND "The value of a is " & a TO DISPLAY SEND "The value of b is " & b TO DISPLAY End Sub PROCEDURE swap (REF a, REF b) SET temp TO a SET a TO b SET b TO temp END PROCEDURE

Reference Parameters Example: Write a program allows the user to swap the positions of any two values in an array

Reference Parameters PROCEDURE swap (REF a, REF b) SET temp TO a SET a TO b SET b TO temp END PROCEDURE

Reference Parameters PROCEDURE main_program_click (REF numbers) Print_array numbers [ ] SEND "Please enter index position 1 to swap" TO DISPLAY RECEIVE index1 FROM KEYBOARD SEND "Please enter index position 2 to swap" TO DISPLAY RECEIVE index2 FROM KEYBOARD swap (numbers [index1], numbers [index2] ) Print_array numbers[ ] END PROCEDURE

Parameter Passing Parameter passing by value creates a copy of the variable when the sub procedure is called - this is inefficient if the variable is an array. Arrays are normally passed as reference parameters because of the memory space they occupy.

Question Examples

SQA 2012 A travel agent uses a suite of software to help advertise holidays and make bookings. Part of the pseudocode that was written for the software is: if cost_per_person is less than 500 set band to ‘cheap’ end if if cost_per_person is greater than or equal to 500 AND cost_per_person is less than 2000 set band to ‘medium’ end if if cost_per_person is greater than or equal to 2000 set band to ‘expensive’ end if

SQA 2012 When the above is implemented as a subroutine, state whether the variable “cost_per_person” would be passed by reference or value. Justify your answer. Each holiday booking is assigned a unique reference code. The software which creates this code uses concatenation within a user-defined function. Explain the term concatenation. Explain the term function.

SQA 2012 The variable cost_per_person” would be passed by value because it is not going to be changed by the program The term concatenation means to join two or more strings together to make one string A function is a section of code which returns a single value

SQA 2010 A teacher tells their pupils that they must avoid the use of global variables in their programs where possible. State the meaning of the term “global variable”. Explain why the pupils have been asked to avoid the unnecessary use of global variables when programming.

SQA 2010 A global variable is a variable which can be accessed throughout a program. Using Global variables can cause unexpected changes if variables with the same name are used in the program The code is less readable because it is not obvious how data is flowing between procedures Memory used by local variables is reused once the procedure has completed its task but global variables will always be using memory resources Procedures declared with parameters can be re-used making the code more modular and the code more portable

SQA 2011 (c) Explain one difference between a procedure and a function A well written program should make use of parameter passing. (i) State the purpose of an in parameter. (ii) State the purpose of an out parameter.

SQA 2011 A function can only return a single value whereas a procedure can return any number of values The value of a function can be assigned to a variable eg. Uservalue = validnumber 1, 10 in parameter: a variable passed into a sub procedure whose value is used but not changed out parameter: a variable passed into a procedure whose value is changed by that procedure

SQA 2010 A tower block has 38 floors, each with 25 rooms. A label for a room will consist of the floor number and the room number. The design for a labelling program is shown below. For each of 38 floors For each of 25 rooms Display “Floor Number:” and floor_no Display “Room Number:” and room_no Next room Display two blank lines Next floor In order for Henry’s program to operate correctly for any office building two parameters would have to be passed to it. (i) State what these two parameters would be. State whether these parameters would be passed to the subprogram by value or by reference. Justify your answer.

SQA 2010 Number of floors in the building (floor_no) Number of rooms on each floor (room_no) These variables would be passed by value since the values are only used, not changed

SQA 2009 A program is created during the implementation stage of the software development process. (a) Programmers may make use of a module library. State what is meant by the term “module library”. (b) The program may require a user-defined function. State what is meant by the term “user- defined function”.

SQA 2009 A module library is a collection of pre-written/pre-tested sections of code which can be re-used A user defined function is one which created by the programmer, not already built in. which returns a single value

SQA 2009 A cinema ticket system allows customers to select and pay for their own tickets. The top level algorithm is: 1. Get ticket details 2. Calculate cost 3. Display cost and accept payment The module CalculateCost uses the number of tickets and the category of ticket to calculate the total payment due. It uses the parameters described below. (a) State the most suitable data type for the parameter called Cost. ParameterDescription AmountNumber of tickets Categoryadult, child, student, OAP CostTotal cost of required tickets

SQA 2009 The module CalculateCost uses the number of tickets and the category ofticket to calculate the total payment due. It uses the parameters described below. The most suitable data type for the parameter Cost is real or currency since it will be storing a decimal value ParameterDescription AmountNumber of tickets Categoryadult, child, student, OAP CostTotal cost of required tickets

SQA Get ticket details 2. Calculate cost 3. Display cost and accept payment Parameters can either be passed by value or by reference. (i) Identify one parameter that is passed by value to the module CalculateCost. Justify your answer. (ii) Identify one parameter that is passed by reference to the module CalculateCost. Justify your answer. ParameterDescription AmountNumber of tickets Categoryadult, child, student, OAP CostTotal cost of required tickets

SQA Get ticket details 2. Calculate cost 3. Display cost and accept payment ParameterDescription AmountNumber of tickets Categoryadult, child, student, OAP CostTotal cost of required tickets Amount or Category can be passed by value into Calculate Cost since they are not being changed Cost will be passed by reference since it is being passed out of Calculate Cost and into the Display cost and accept payment procedure

SQA 2009 (c) A program may use local variables and global variables. (i)What is the scope of a global variable? (ii) State two advantages of using parameter passing rather than global variables when programming.

SQA 2009 The scope of a global variable is throughout the program. The advantages of using parameter passing rather than global variables is to increase the modularity, portability readability and maintainability of the code.

SQA 2009 The program will make use of a 1-D array. (i)When creating, or declaring, a 1-D array for use in a program, a name must be given to the array. State two other items that should be specified when the array is created. (ii) Explain why it is a more efficient use of system resources to pass an array by reference rather than by value.

SQA 2009 (i)When creating, or declaring, a 1-D array you need to state the number of items in the array (its index) and the data type (integer, string boolean etc) (ii) Passing an array by reference is more efficient than passing by value because arrays consume large amounts of memory and since when a parameter is passed by value, a copy is made, memory is consumed unnecessarily.

2008 A holiday booking website includes a currency converter which asks for the amount in pounds sterling and converts it to euros. Here is the top- level algorithm, including data flow for steps 1 and get amount of pounds (out: pounds) 2. calculate euros (in: pounds out: euros) 3. display conversion (a)State which design notation is being used. (b) Step 3 results in the following being displayed on screen: £500 converts to 750 euros. State the data flow for step 3. (c) Identify whether the pounds variable in step 1 should be passed by value or passed by reference. Explain your answer.

get amount of pounds (out: pounds) 2. calculate euros (in: pounds out: euros) 3. display conversion (a)The design notation being used is pseudocode (b) The data flow for step 3 is (in: pounds in: euros) (c) In step 1 pounds should be passed by reference because it is being given a value which is then passed out of step 1 and into steps 2 and 3

SQA 2008 During the development of the software, module libraries are used. The modules limit the scope of certain variables. (i) What is a module library? (ii) Describe one way in which the scope of a variable may be limited. (iii) Explain why the programmer might want to limit the scope of a variable.

Another example The design for a program is shown below. 1. Initialise variables 2. Enter pupil marks 3. Count the number of pupils with less than 45 marks 4. Display results. (b) Step 3 of the program uses the parameters PupilMark and NoNeedingSupport. (i) State the variable types for these parameters. (ii) For each parameter, state if it should passed by value or by reference in step 3?

Another example The design for a program is shown below. 1. Initialise variables 2. Enter pupil marks 3. Count the number of pupils with less than 45 marks 4. Display results. (i) and NoNeedingSupport would integer (ii) In step 3, PupilMark would be passed by value and NoNeedingSupport would be passed by reference (because it is passed out and then into step 4)

Summary A Local variable only has scope within the-sub procedure where it has been defined. A global variable has scope throughout a program. Using global variables makes code less readable, less modular and thus less maintainable A value parameter is one which is passed into a sub-procedure and whose value is copied, used by that procedure then discarded. A reference parameter is a variable which is passed into a sub-procedure and then out again and whose value is changed by that sub- procedure The advantages of using parameter passing rather than global variables is to increase the modularity, portability readability and maintainability of the code. A function returns a value, a procedure performs a sequence of actions A built in function is supplied as part of the development environment, a user defined function is one created by the programmer.