SlideShare a Scribd company logo
1 of 37
CSWD1001
Programming Methods
Function
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
1
What we’ll learn
• Introduction to functions
• Writing your own functions
• More library functions
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
2
What is Function
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
3
Definition
• A functions is a module that returns a value back to the part
of the program that called it
• Most programming languages provide a library of prewritten
functions that perform commonly needed tasks.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
4
Remember Function
is
Different
from Module
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
5
• Functions are called differently than modules
• In pseudocode, you use the Call statement to call a module.
You do not use the Call statement to call a function.
• Function calls are
• usually inserted into statements that perform some operation with
the value that is returned from the function.
• might also be inserted into a Display statement that displays the
value that is returned from the function.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
6
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
7
Library Function
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
8
Characteristic of Library Function
• Library function:
• Are built into the programming language, and you can call them any time you
need them
• Usually stored in special files
• When you call a library function in one of your programs, the
compiler or interpreter automatically causes the function to execute,
without requiring the function’s code to appear in your program.
• You never have to see the code for a library function – you only need
to know the purpose of the library function, the arguments that you
must pass to it, and what type of data it returns.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
9
Example – Random function
• Commonly used in games, example computer games that let the player
roll dice use random numbers to represent the values of the dice
• Useful in simulation programs. Formulas can be constructed in which
a random number is used to determine various actions and events that
take place in the program
• Useful in statistical programs that must randomly select data for
analysis
• Commonly used in computer security to encrypt sensitive data
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
10
Pseudocode
// Declare a variable to control the loop iterations.
Declare String again
Do
// Roll the dice.
Display "Rolling the dice..."
Display "Their values are:"
Display random(1, 6)
Display random(1, 6)
// Do this again?
Display "Want to roll them again? (y = yes)"
Input again
While again == "y" OR again == "Y"
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
11
Flowchart
Start
Declare String again
Display “Rolling the dice…”
Display “Their values are.”
Display random(1,6)
Display random(1,6)
Display “Want to roll tem again?
(y = yes)”
Input again
again ==
“y” OR
again ==
“Y”
End
True
False
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
12
More library function – mathematical
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
13
More library function – data type conversion
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
14
More library function – string function
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
15
You can Write your Own Function
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
16
Characteristic of Own Function
• Most programming languages allow you to write your own
functions.
• When you write a function, you are essentially writing a
module that can send a value back to the part of the program
that called it
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
17
Declaration of Function
Function DataType FunctionName(ParameterList)
Statement
Statement
Statement
Etc
Return value
End Fuction
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
18
Example Use Case Writing own Function
• Hal owns a business named Make Your Own Music, which sells
guitars, drums, banjos, synthesizers, and many other musical
instruments.
• Hal’s sales staff works strictly on commission. At the end of the
month, each salesperson’s commission is calculated according to table
below:
Sales This Month Commission Rate
Less than $10, 000.00 10%
$10,000.00 – 14, 999.99 12%
$15,000.00 – 17, 999.99 14%
$18,000.00 – 21, 999.99 16%
$22,000.00 or more 18%
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
19
• For example, a salesperson with $16,000 in monthly sales will earn a
14 percent commission ($2,240). Another salesperson with $20,000 in
monthly sales will earn a 16 percent commission ($3,200). A person
with $30,000 in sales will earn an 18 percent commission ($5,400).
• Because the staff gets paid once per month, Hal allows each employee
to take up to $2,000 per month in advance. When sales commissions
are calculated, the amount of each employee’s advanced pay is
subtracted from the commission.
• If any salesperson’s commission is less than the amount of his or her
advance, the salesperson must reimburse Hal for the difference.
• To calculate a salesperson’s monthly pay, Hal uses the following
formula:
Pay = Sales × Commission rate – Advanced pay
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
20
• Hal has asked you to write a program that makes this calculation for
him. The following general algorithm outlines the steps the program
must take:
1. Get the salesperson’s monthly sales.
2. Get the amount of advanced pay.
3. Use the amount of monthly sales to determine the commission rate.
4. Calculate the salesperson’s pay using the formula previously shown. If the
amount is negative, indicate that the salesperson must reimburse the
company.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
21
Pseudocode Commission Rate Program:
Main Module
Module main()
// Local variables
Declare Real sales, commissionRate, advancedPay
// Get the amount of sales.
Set sales = getSales()
// Get the amount of advanced pay.
Set advancedPay = getAdvancedPay()
// Determine the commission rate.
Set commissionRate = determineCommissionRate(sales)
// Calculate the pay.
Set pay = sales * commissionRate - advancedPay
// Display the amount of pay.
Display "The pay is $", pay
// Determine whether the pay is negative.
If pay < 0 Then
Display "The salesperson must reimburse the
company."
End If
End Module
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
22
Pseudocode Commission Rate Program:
getSales Function
// The getSales function gets a salesperson's monthly sales from the user and returns
// that value as a Real.
Function Real getSales()
// Local variable to hold the monthly sales.
Declare Real monthlySales
// Get the amount of monthly sales.
Display "Enter the salesperson's monthly sales."
Input monthlySales
// Return the amount of monthly sales.
Return monthlySales
End Function
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
23
Pseudocode Commission Rate Program:
getadvancedpay Function
// The getAdvancedPay function gets the amount of // advanced pay given to the salesperson and
// returns that amount as a Real.
Function Real getAdvancedPay()
// Local variable to hold the advanced pay.
Declare Real advanced
// Get the amount of advanced pay.
Display "Enter the amount of advanced pay, or 0 if no advanced pay was given."
Input advanced
// Return the advanced pay.
Return advanced
End Function
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
24
Pseudocode Commission Rate Program:
determineCommissionRate Function
//The determineCommissionRate function accepts the
// amount of sales as an argument and returns the
// commission rate as a Real.
Function Real determineCommissionRate(Real sales)
// Local variable to hold commission rate.
Declare Real rate
// Determine the commission rate.
If sales < 10000.00 Then
Set rate = 0.10
Else If sales >= 10000.00 AND sales <= 14999.99 Then
Set rate = 0.12
Else If sales >= 15000.00 AND sales <= 17999.99 Then
Set rate = 0.14
Else If sales >= 18000.00 AND sales <= 21999.99 Then
Set rate = 0.16
Else
Set rate = 0.18
End If
// Return the commission rate.
Return rate
End Function
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
25
Flowchart
Main Module
Main()
Declare Real sales,
commissionRate, advancedPay
Set sales = getSales()
Set advancedPay =
getAdvancedPay()
Set commissionRate =
determineCommissionRate(sales)
Set pay = sales *
commissionRate - advancedPay
Display “The pay
is $”, pay
pay < 0
End
Display “The
salesperson must
reimburse the
company ”
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
26
Flowchart
getSales
Function
getSales()
Declare Real monthlySales
Display “Enter the
sales-person’s
monthly sa;es”
Input monthlySales
Return
monthlySales
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
27
Flowchart
getadvancedpay
Function
getAdvancedpay()
Declare Real adanced
Display “Enter the
amount of advanced
pay, or 0 if no advanced
pay was given”
Input advanced
Return
advanced
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
28
Flowchart
determineComm
issionRate
Function
determineCom
missionRate(Re
al sales)
Declare Real rate
Sales <
10000.00
Set rate = 0.10
Sales >=
10000.00
AND sales
<=
14999.99
Sales >=
15000.00
AND sales
<=
17999.99
Sales >=
18000.00
AND sales
<=
21999.99
Set rate = 0.12
Set rate = 0.14
Set rate = 0.16Set rate = 0.18
Return rate
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
29
Using IPO Charts
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
30
Definition
• IPO stands for input, processing, and output, and an IPO chart
describes the input, processing, and output of a function.
• Simple but effective tool that programmers sometimes use while
designing functions
• These items are usually laid out in columns:
• the input column - description of the data that is passed to the function as
arguments;
• the processing column - description of the process that the function
performs;and
• the output column - describes the data that is returned from the function.
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
31
IPO charts for the getRegularPrice and
discount functions
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
32
Pseudocode
// Global constant for the discount percentage.
Constant Real DISCOUNT_PERCENTAGE = 0.20
// The main module is the program's starting point.
Module main()
// Local variables to hold regular and sale
prices.
Declare Real regularPrice, salePrice
// Get the item's regular price.
Set regularPrice = getRegularPrice()
// Calculate the sale price.
Set salePrice = regularPrice -
discount(regularPrice)
// Display the sale price.
Display "The sale price is $", salePrice
End Module
// The getRegularPrice function prompts the user to
// enter an item's regular price and returns that
// value as a Real.
Function Real getRegularPrice()
// Local variable to hold the price.
Declare Real price
// Get the regular price.
Display "Enter the item's regular price."
Input price
// Return the regular price.
Return price
End Function
// The discount function accepts an item's price
// as an argument and returns the amount of the
// discount specified by DISCOUNT_PERCENTAGE.
Function Real discount(Real price)
Return price * DISCOUNT_PERCENTAGE
End Function
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
33
Function allow
a Return
as
Strings / Boolean
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
34
Functions That Return Strings
Function String getName()
//Local variable to hold the user’s name
Declare String name
//Get the user’s name
Display “Enter your name”
Input name
//Return the name
Return name
End Function
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
35
Functions That Return Either True Or False
Function Boolean isEvent(Integer number)
//Local variable to hold True or False
Declare Boolean status
//Determine whether number is even. If it is, set status to
true. Otherwise, set status to false.
If number MOD 2 == 0 Then
Set status = True
Else
Set status = False
// Return the value in the status variable
Return status
End Function
If isEven(number) Then
Display “The number is even”
Else
Display “The number is odd”
End If
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
36
Summary
• A function is a module that returns a value back to the part of the
program that called it. Most programming languages provide a library
of prewritten functions that perform commonly needed tasks. In these
libraries you typically find a function that generates random numbers.
• Most programming languages allow you to write your own functions.
When you write a function, you are essentially writing a module that
can send a value back to the part of the program that called it.
• An IPO chart is a simple but effective tool that programmers
sometimes use while designing functions
18/9/2018
CSWD1001 @ Kwan Lee First City Unversity Malaysia
(FCUC)
37

More Related Content

Similar to 6 Function

Pseudocode algorithim flowchart
Pseudocode algorithim flowchartPseudocode algorithim flowchart
Pseudocode algorithim flowchartfika sweety
 
Risk & capital budgeting
Risk & capital  budgetingRisk & capital  budgeting
Risk & capital budgetinglubnasadiyah
 
List of programs to practice for ICSE
List of programs to practice for ICSEList of programs to practice for ICSE
List of programs to practice for ICSEMokshya Priyadarshee
 
Print Vision Presentation (August 2008)
Print Vision Presentation (August 2008)Print Vision Presentation (August 2008)
Print Vision Presentation (August 2008)Jon Hansen
 
SE 307-CHAPTER_9_PROJECT_CASH_FLOW_ANALYSIS.ppt
SE 307-CHAPTER_9_PROJECT_CASH_FLOW_ANALYSIS.pptSE 307-CHAPTER_9_PROJECT_CASH_FLOW_ANALYSIS.ppt
SE 307-CHAPTER_9_PROJECT_CASH_FLOW_ANALYSIS.pptAishaKhan527933
 
A Study in the use of BPM to increase profits By David Key, Stephen Justice a...
A Study in the use of BPM to increase profits By David Key, Stephen Justice a...A Study in the use of BPM to increase profits By David Key, Stephen Justice a...
A Study in the use of BPM to increase profits By David Key, Stephen Justice a...E Squared UK Ltd
 
Week14_Business Simulation Modeling MSBA.pptx
Week14_Business Simulation Modeling MSBA.pptxWeek14_Business Simulation Modeling MSBA.pptx
Week14_Business Simulation Modeling MSBA.pptxUsamamalik345378
 
Part I (Short Answer)1. In Java, what are the three different w.docx
Part I (Short Answer)1. In Java, what are the three different w.docxPart I (Short Answer)1. In Java, what are the three different w.docx
Part I (Short Answer)1. In Java, what are the three different w.docxherbertwilson5999
 
cost_and_management_acc_accounting-manual
cost_and_management_acc_accounting-manualcost_and_management_acc_accounting-manual
cost_and_management_acc_accounting-manualmuumaimar
 
Chapter 10 Cash Flow Estimation
Chapter 10 Cash Flow EstimationChapter 10 Cash Flow Estimation
Chapter 10 Cash Flow EstimationAlamgir Alwani
 
exploring_a03_grader_h3.accdb (solution)
exploring_a03_grader_h3.accdb (solution)exploring_a03_grader_h3.accdb (solution)
exploring_a03_grader_h3.accdb (solution)JackCandtona
 
NCV 2 Entrepreneurship Hands-On Support Slide Show - Module 3
NCV 2 Entrepreneurship Hands-On Support Slide Show -  Module 3NCV 2 Entrepreneurship Hands-On Support Slide Show -  Module 3
NCV 2 Entrepreneurship Hands-On Support Slide Show - Module 3Future Managers
 
Management consultancy-chapter-26-and-35
Management consultancy-chapter-26-and-35Management consultancy-chapter-26-and-35
Management consultancy-chapter-26-and-35Holy Cross College
 

Similar to 6 Function (16)

Pseudocode algorithim flowchart
Pseudocode algorithim flowchartPseudocode algorithim flowchart
Pseudocode algorithim flowchart
 
Risk & capital budgeting
Risk & capital  budgetingRisk & capital  budgeting
Risk & capital budgeting
 
List of programs to practice for ICSE
List of programs to practice for ICSEList of programs to practice for ICSE
List of programs to practice for ICSE
 
Print Vision Presentation (August 2008)
Print Vision Presentation (August 2008)Print Vision Presentation (August 2008)
Print Vision Presentation (August 2008)
 
SE 307-CHAPTER_9_PROJECT_CASH_FLOW_ANALYSIS.ppt
SE 307-CHAPTER_9_PROJECT_CASH_FLOW_ANALYSIS.pptSE 307-CHAPTER_9_PROJECT_CASH_FLOW_ANALYSIS.ppt
SE 307-CHAPTER_9_PROJECT_CASH_FLOW_ANALYSIS.ppt
 
A Study in the use of BPM to increase profits By David Key, Stephen Justice a...
A Study in the use of BPM to increase profits By David Key, Stephen Justice a...A Study in the use of BPM to increase profits By David Key, Stephen Justice a...
A Study in the use of BPM to increase profits By David Key, Stephen Justice a...
 
Week14_Business Simulation Modeling MSBA.pptx
Week14_Business Simulation Modeling MSBA.pptxWeek14_Business Simulation Modeling MSBA.pptx
Week14_Business Simulation Modeling MSBA.pptx
 
8 Array
8 Array8 Array
8 Array
 
Part I (Short Answer)1. In Java, what are the three different w.docx
Part I (Short Answer)1. In Java, what are the three different w.docxPart I (Short Answer)1. In Java, what are the three different w.docx
Part I (Short Answer)1. In Java, what are the three different w.docx
 
cost_and_management_acc_accounting-manual
cost_and_management_acc_accounting-manualcost_and_management_acc_accounting-manual
cost_and_management_acc_accounting-manual
 
Acct 505 final exam
Acct 505 final examAcct 505 final exam
Acct 505 final exam
 
Breakeven analysis.pdf
Breakeven analysis.pdfBreakeven analysis.pdf
Breakeven analysis.pdf
 
Chapter 10 Cash Flow Estimation
Chapter 10 Cash Flow EstimationChapter 10 Cash Flow Estimation
Chapter 10 Cash Flow Estimation
 
exploring_a03_grader_h3.accdb (solution)
exploring_a03_grader_h3.accdb (solution)exploring_a03_grader_h3.accdb (solution)
exploring_a03_grader_h3.accdb (solution)
 
NCV 2 Entrepreneurship Hands-On Support Slide Show - Module 3
NCV 2 Entrepreneurship Hands-On Support Slide Show -  Module 3NCV 2 Entrepreneurship Hands-On Support Slide Show -  Module 3
NCV 2 Entrepreneurship Hands-On Support Slide Show - Module 3
 
Management consultancy-chapter-26-and-35
Management consultancy-chapter-26-and-35Management consultancy-chapter-26-and-35
Management consultancy-chapter-26-and-35
 

Recently uploaded

Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...EduSkills OECD
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFVivekanand Anglo Vedic Academy
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code ExamplesPeter Brusilovsky
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismDabee Kamal
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxCeline George
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhleson0603
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSean M. Fox
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppCeline George
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....Ritu480198
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital ManagementMBA Assignment Experts
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptxPoojaSen20
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesAmanpreetKaur157993
 

Recently uploaded (20)

Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptx
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 

6 Function

  • 1. CSWD1001 Programming Methods Function 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 1
  • 2. What we’ll learn • Introduction to functions • Writing your own functions • More library functions 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 2
  • 3. What is Function 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 3
  • 4. Definition • A functions is a module that returns a value back to the part of the program that called it • Most programming languages provide a library of prewritten functions that perform commonly needed tasks. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 4
  • 5. Remember Function is Different from Module 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 5
  • 6. • Functions are called differently than modules • In pseudocode, you use the Call statement to call a module. You do not use the Call statement to call a function. • Function calls are • usually inserted into statements that perform some operation with the value that is returned from the function. • might also be inserted into a Display statement that displays the value that is returned from the function. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 6
  • 7. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 7
  • 8. Library Function 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 8
  • 9. Characteristic of Library Function • Library function: • Are built into the programming language, and you can call them any time you need them • Usually stored in special files • When you call a library function in one of your programs, the compiler or interpreter automatically causes the function to execute, without requiring the function’s code to appear in your program. • You never have to see the code for a library function – you only need to know the purpose of the library function, the arguments that you must pass to it, and what type of data it returns. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 9
  • 10. Example – Random function • Commonly used in games, example computer games that let the player roll dice use random numbers to represent the values of the dice • Useful in simulation programs. Formulas can be constructed in which a random number is used to determine various actions and events that take place in the program • Useful in statistical programs that must randomly select data for analysis • Commonly used in computer security to encrypt sensitive data 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 10
  • 11. Pseudocode // Declare a variable to control the loop iterations. Declare String again Do // Roll the dice. Display "Rolling the dice..." Display "Their values are:" Display random(1, 6) Display random(1, 6) // Do this again? Display "Want to roll them again? (y = yes)" Input again While again == "y" OR again == "Y" 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 11
  • 12. Flowchart Start Declare String again Display “Rolling the dice…” Display “Their values are.” Display random(1,6) Display random(1,6) Display “Want to roll tem again? (y = yes)” Input again again == “y” OR again == “Y” End True False 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 12
  • 13. More library function – mathematical 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 13
  • 14. More library function – data type conversion 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 14
  • 15. More library function – string function 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 15
  • 16. You can Write your Own Function 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 16
  • 17. Characteristic of Own Function • Most programming languages allow you to write your own functions. • When you write a function, you are essentially writing a module that can send a value back to the part of the program that called it 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 17
  • 18. Declaration of Function Function DataType FunctionName(ParameterList) Statement Statement Statement Etc Return value End Fuction 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 18
  • 19. Example Use Case Writing own Function • Hal owns a business named Make Your Own Music, which sells guitars, drums, banjos, synthesizers, and many other musical instruments. • Hal’s sales staff works strictly on commission. At the end of the month, each salesperson’s commission is calculated according to table below: Sales This Month Commission Rate Less than $10, 000.00 10% $10,000.00 – 14, 999.99 12% $15,000.00 – 17, 999.99 14% $18,000.00 – 21, 999.99 16% $22,000.00 or more 18% 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 19
  • 20. • For example, a salesperson with $16,000 in monthly sales will earn a 14 percent commission ($2,240). Another salesperson with $20,000 in monthly sales will earn a 16 percent commission ($3,200). A person with $30,000 in sales will earn an 18 percent commission ($5,400). • Because the staff gets paid once per month, Hal allows each employee to take up to $2,000 per month in advance. When sales commissions are calculated, the amount of each employee’s advanced pay is subtracted from the commission. • If any salesperson’s commission is less than the amount of his or her advance, the salesperson must reimburse Hal for the difference. • To calculate a salesperson’s monthly pay, Hal uses the following formula: Pay = Sales × Commission rate – Advanced pay 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 20
  • 21. • Hal has asked you to write a program that makes this calculation for him. The following general algorithm outlines the steps the program must take: 1. Get the salesperson’s monthly sales. 2. Get the amount of advanced pay. 3. Use the amount of monthly sales to determine the commission rate. 4. Calculate the salesperson’s pay using the formula previously shown. If the amount is negative, indicate that the salesperson must reimburse the company. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 21
  • 22. Pseudocode Commission Rate Program: Main Module Module main() // Local variables Declare Real sales, commissionRate, advancedPay // Get the amount of sales. Set sales = getSales() // Get the amount of advanced pay. Set advancedPay = getAdvancedPay() // Determine the commission rate. Set commissionRate = determineCommissionRate(sales) // Calculate the pay. Set pay = sales * commissionRate - advancedPay // Display the amount of pay. Display "The pay is $", pay // Determine whether the pay is negative. If pay < 0 Then Display "The salesperson must reimburse the company." End If End Module 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 22
  • 23. Pseudocode Commission Rate Program: getSales Function // The getSales function gets a salesperson's monthly sales from the user and returns // that value as a Real. Function Real getSales() // Local variable to hold the monthly sales. Declare Real monthlySales // Get the amount of monthly sales. Display "Enter the salesperson's monthly sales." Input monthlySales // Return the amount of monthly sales. Return monthlySales End Function 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 23
  • 24. Pseudocode Commission Rate Program: getadvancedpay Function // The getAdvancedPay function gets the amount of // advanced pay given to the salesperson and // returns that amount as a Real. Function Real getAdvancedPay() // Local variable to hold the advanced pay. Declare Real advanced // Get the amount of advanced pay. Display "Enter the amount of advanced pay, or 0 if no advanced pay was given." Input advanced // Return the advanced pay. Return advanced End Function 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 24
  • 25. Pseudocode Commission Rate Program: determineCommissionRate Function //The determineCommissionRate function accepts the // amount of sales as an argument and returns the // commission rate as a Real. Function Real determineCommissionRate(Real sales) // Local variable to hold commission rate. Declare Real rate // Determine the commission rate. If sales < 10000.00 Then Set rate = 0.10 Else If sales >= 10000.00 AND sales <= 14999.99 Then Set rate = 0.12 Else If sales >= 15000.00 AND sales <= 17999.99 Then Set rate = 0.14 Else If sales >= 18000.00 AND sales <= 21999.99 Then Set rate = 0.16 Else Set rate = 0.18 End If // Return the commission rate. Return rate End Function 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 25
  • 26. Flowchart Main Module Main() Declare Real sales, commissionRate, advancedPay Set sales = getSales() Set advancedPay = getAdvancedPay() Set commissionRate = determineCommissionRate(sales) Set pay = sales * commissionRate - advancedPay Display “The pay is $”, pay pay < 0 End Display “The salesperson must reimburse the company ” 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 26
  • 27. Flowchart getSales Function getSales() Declare Real monthlySales Display “Enter the sales-person’s monthly sa;es” Input monthlySales Return monthlySales 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 27
  • 28. Flowchart getadvancedpay Function getAdvancedpay() Declare Real adanced Display “Enter the amount of advanced pay, or 0 if no advanced pay was given” Input advanced Return advanced 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 28
  • 29. Flowchart determineComm issionRate Function determineCom missionRate(Re al sales) Declare Real rate Sales < 10000.00 Set rate = 0.10 Sales >= 10000.00 AND sales <= 14999.99 Sales >= 15000.00 AND sales <= 17999.99 Sales >= 18000.00 AND sales <= 21999.99 Set rate = 0.12 Set rate = 0.14 Set rate = 0.16Set rate = 0.18 Return rate 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 29
  • 30. Using IPO Charts 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 30
  • 31. Definition • IPO stands for input, processing, and output, and an IPO chart describes the input, processing, and output of a function. • Simple but effective tool that programmers sometimes use while designing functions • These items are usually laid out in columns: • the input column - description of the data that is passed to the function as arguments; • the processing column - description of the process that the function performs;and • the output column - describes the data that is returned from the function. 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 31
  • 32. IPO charts for the getRegularPrice and discount functions 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 32
  • 33. Pseudocode // Global constant for the discount percentage. Constant Real DISCOUNT_PERCENTAGE = 0.20 // The main module is the program's starting point. Module main() // Local variables to hold regular and sale prices. Declare Real regularPrice, salePrice // Get the item's regular price. Set regularPrice = getRegularPrice() // Calculate the sale price. Set salePrice = regularPrice - discount(regularPrice) // Display the sale price. Display "The sale price is $", salePrice End Module // The getRegularPrice function prompts the user to // enter an item's regular price and returns that // value as a Real. Function Real getRegularPrice() // Local variable to hold the price. Declare Real price // Get the regular price. Display "Enter the item's regular price." Input price // Return the regular price. Return price End Function // The discount function accepts an item's price // as an argument and returns the amount of the // discount specified by DISCOUNT_PERCENTAGE. Function Real discount(Real price) Return price * DISCOUNT_PERCENTAGE End Function 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 33
  • 34. Function allow a Return as Strings / Boolean 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 34
  • 35. Functions That Return Strings Function String getName() //Local variable to hold the user’s name Declare String name //Get the user’s name Display “Enter your name” Input name //Return the name Return name End Function 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 35
  • 36. Functions That Return Either True Or False Function Boolean isEvent(Integer number) //Local variable to hold True or False Declare Boolean status //Determine whether number is even. If it is, set status to true. Otherwise, set status to false. If number MOD 2 == 0 Then Set status = True Else Set status = False // Return the value in the status variable Return status End Function If isEven(number) Then Display “The number is even” Else Display “The number is odd” End If 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 36
  • 37. Summary • A function is a module that returns a value back to the part of the program that called it. Most programming languages provide a library of prewritten functions that perform commonly needed tasks. In these libraries you typically find a function that generates random numbers. • Most programming languages allow you to write your own functions. When you write a function, you are essentially writing a module that can send a value back to the part of the program that called it. • An IPO chart is a simple but effective tool that programmers sometimes use while designing functions 18/9/2018 CSWD1001 @ Kwan Lee First City Unversity Malaysia (FCUC) 37