Вы находитесь на странице: 1из 57

Intro to Programming

& Algorithm Design


Functions

Assg

This presentation can be viewed on line in a file named:


1
ch06.IntrotoProg.Functions.ppt
Copyright 2003 by Janson Industries
Objectives
▀ Explain
■ What a function is
■ How to use and create
functions
■ IPO Charts

▀ Show how to implement and


use functions in Java

2
Copyright 2016 by Janson Industries
Function
▀ Per text: “Functions are methods/
modules that return a value”
▀ Just as with methods, the function
header defines the function's
■ Name
■ Expected values (arguments)
▀ The function header also defines
■ The returned value type (Real, String)
▀ And the body must contain
■ A Return statement
3
Copyright 2016 by Janson Industries
Function
▀ In pseudocode, function starts
with the word Function and ends
with End Function

Function String captureInput()


Declare String data
Display “Enter input”
Input data
Return data
End Function

4
Copyright 2016 by Janson Industries
Function
▀ A function's returned value can be
assigned to a variable
▀ Call a function just like a module:
■ Specify the function name
followed by parenthesis
Module main()
Declare String subtotal
subtotal = captureInput()
End Module

▀ Does captureInput accept any


data? 5
Copyright 2016 by Janson Industries
All Pseudocode
Module main()
Declare String subtotal
subtotal = captureInput()
End Module

Function String captureInput()


Declare String data
Display “Enter input”
Input data
Return data
End Function 6
Copyright 2016 by Janson Industries
Function Calls Flowchart
main() captureInput()

Declare String Declare String


subtotal data

subtotal = Display “Enter input”


captureInput()

Display subtotal Input data

End Return data


7
Copyright 2016 by Janson Industries
Flowgorithm

Function name

The return value type

The variable/value to return

Copyright 2016 by Janson Industries


Then add function
statements

Flowgorithm

Copyright 2016 by Janson Industries


Flowgorithm
Finished function

Copyright 2016 by Janson Industries


Flowgorithm

When run

Copyright 2016 by Janson Industries


The return value type
Function name

The value/variable to return

Copyright 2016 by Janson Industries


Functions
▀ Can also accept data
■ Just like modules

▀ Will create a function called


print() to:
■ Accept a String
■ Display the String
■ Return the String "Did it"

13
Copyright 2016 by Janson Industries
Functions
▀ main() will:
■ Call print() and pass the String
"Howdy"
■ Store the String passed back by
print in a variable called
returnedValue
■ Display the text "returnedValue
= " and the value of the variable
returnedValue

14
Copyright 2016 by Janson Industries
Pseudocode
Function String print(String stringVar)
Display stringVar
Return "Did it"
End Function

Module main()
Declare String returnedValue
returnedValue = print("Howdy")
Display "returnedValue = ", returnedValue
End Module
15
Copyright 2016 by Janson Industries
Flowgorithm Functions

Function name

Parameter type and


variable to hold value

Returned value data


type and value 16
Copyright 2016 by Janson Industries
Flowgorithm Functions
When run

print() displays

main() displays

17
Copyright 2016 by Janson Industries
Java
▀ Java very similar to pseudocode
The return value type
Parameter type Variable name
Function name

The value/variable to return

Copyright 2016 by Janson Industries


Prewritten Functions
▀ Supplied with programming
language
▀ Example: System.out.println() the
println function is invoked in a
class called System
■ You can tell because () follows
the name

▀ This is an example of a function


that will accept a parameter
■ System.out.println("Stuff");
19
Copyright 2016 by Janson Industries
Why Create Functions
▀ Just as with methods, functions
cut down on duplicate code
▀ Make it easier for programmer
▀ For instance, System.out.println()
is a lot to type
▀ Will create a class called MyUtils
■ Create a function called p(String output)
■ Will be able to specify MyUtils.p()
instead of System.out.println() 20
Copyright 2016 by Janson Industries
Pre-Written functions
▀ MyUtils will act as a repository of
useful functions
■ So, no need for a main()

public class MyUtils {

public static int p(String output){


System.out.println(output);
return 1;
}
}

21
Copyright 2016 by Janson Industries
Pre-Written Functions
▀ Now any other class can use the
function p()
▀ In any java class, just specify
■ ClassName.functionName();
public class FunctionCall2 {

public static void main(String[] args) {


MyUtils.p(“Howdy”);
}
}
22
Copyright 2016 by Janson Industries
When FunctionCall2 is run, it invokes p in MyUtils

Must compile MyUtils before FunctionCall2

23
Copyright 2016 by Janson Industries
Prewritten Functions
▀ Most languages come with many
to perform common functions
■ Mathematical functions
♦ Sine, cosine, square root, etc.
■ Generate a random number
■ Convert between data types
■ Displaying (println)
■ Exiting
■ Security
♦ Userid/PW, cryptography 24
Copyright 2016 by Janson Industries
Prewritten Functions
▀ Advantage of prewritten functions
■ Don't have to create the function
yourself
■ Don't have to understand how it
works
♦ Called implementation hiding
■ You're sure they work

25
Copyright 2016 by Janson Industries
Prewritten Functions
▀ Some examples
■ random(#,#) – returns a number
between the first (inclusive) and
second number (inclusive)
♦ random(1,6) returns a number
between 1 and 6
■ pow(#,#) – raises the first number to
the power of the second number
♦ pow(2,4) returns 16
■ round(#.#) – returns an integer
value for a real value
♦ round(3.49) returns 3
♦ round(3.5) returns 4 26
Copyright 2016 by Janson Industries
Prewritten Functions
▀ Some examples
■ isInteger(String) – returns a Boolean
value based on whether the string
can be converted to an integer
♦ isInteger("6") returns a value of true
■ isReal(String) – returns a Boolean
value based on whether the string
can be converted to a Real
♦ isReal(“abc”) returns a value of false

27
Copyright 2016 by Janson Industries
Prewritten Functions
▀ Converting data types
▀ With GUIs all data entered is String,
must convert to get numeric value
■ stringToInteger(String) – returns the
integer value of the string
♦ stringToInteger(“6”) returns the number 6
■ stringToReal(String)– returns the real
value of the string
♦ stringToReal(“2.14”) returns the number
2.14

28
Copyright 2016 by Janson Industries
Prewritten Functions
▀ String functions
■ length(String) – returns the number of
characters in a string
♦ length(“hello”) returns the number 5
■ substring(String, 3, 5)– returns the
characters from position 3 to 5
♦ substring(“goodbye”, 3, 5) returns the
string “db”
■ contains(String, String)– returns
Boolean value of true or false based
on if the first string contains the
characters in the second string
♦ contains(“goodbye”, “oo”) returns the 29
Copyright 2016 by Janson Industries value true
Prewritten Functions
▀ String functions – when use?
■ User must enter a new password of at
least 8 characters.
♦ While (length(password) < 8)
• Display "Please enter a password of at least
8 characters"
• Input password
♦ End While

■ User must enter a valid email address


♦ While (!(contains(eMailAddr, “@”))
• Display "Please enter a valid email address"
• Input eMailAddr
♦ End While
30
Copyright 2016 by Janson Industries
Prewritten Functions
▀ String functions – when use?
■ Want to build a user id that consists
of first letter of FN, first letter of
Middle Name (MN), and the full last
name (LN)
♦ String userid = substring(FN, 0, 1) ,
substring(MN, 0, 1) , LN
■ Trim off a blank space
♦ If (substring(amount, length(amount) -1,
length(amount)) = " ") Then
• amount = substring(amount, 0,
length(amount) – 1)
♦ End If
31
Copyright 2016 by Janson Industries
Prewritten Functions Example
▀ Will enhance the captureInput
function to convert the data into a
numeric value

Module main()
Declare Real subtotal
subtotal = captureInput()
Display "2 X " , subtotal, " = ", subtotal*2
End Module

32
Copyright 2016 by Janson Industries
Prewritten Functions Example

Function Real captureInput()


Declare String data
Declare Real numberInput
Display “Enter a number”
Input data
numberInput = stringToReal(data)
Return numberInput
End Function

33
Copyright 2016 by Janson Industries
Prewritten Functions Flowgorithm
▀ Random(#) - returns a random
number between 0 and # - 1
■ Random(6) will return a 0, 1, 2, 3, 4,
or 5

▀ Len(String) – returns the number


of characters in a String
■ Len("goodbye") will return 7

▀ Sqrt(#) – returns the square root


of a number
■ Sqrt(16) will return 4 34
Copyright 2016 by Janson Industries
Data Conversion - Flowgorithm
▀ ToInteger(String) and
ToReal(String) return a numeric
value for the String

▀ ToString(#) – returns a number


as a String

35
Copyright 2016 by Janson Industries
Data Conversion - Flowgorithm

36
Copyright 2016 by Janson Industries
Data Conversion - Flowgorithm

When run

37
Copyright 2016 by Janson Industries
Prewritten Functions Java
▀ Are in classes like Math, Integer,
Double, String
■ Math.pow(#,#) – raises the first
number to the power of the second
number
♦ Math.pow(2,4) returns 16
■ Math.round(#.#) – returns an integer
value for a real value
♦ Math.round(3.49) returns 3
♦ Math.round(3.5) returns 4

38
Copyright 2016 by Janson Industries
Prewritten Functions Java
▀ Some examples
■ Math.random() – returns a number
between 0 and 1(exclusive)
♦ To get an int in a range, must multiply
the result by the max value & add one,
then change to an int (truncate)
• (int) (Math.random()*6) +1

■ Random class has nextInt(#) method


that returns a number from a range
0(inclusive) to #(exclusive)
♦ Random randNumGenerator = new
Random();
♦ randNumGenerator.nextInt(7)
• Returns integer value of 0, 1, 2, 3, 4, 5, or 6 39
Copyright 2016 by Janson Industries
Prewritten Functions Java
▀ Converting data types
▀ With GUIs, all data entered is
String must convert to get
numeric value
■ Integer.valueOf("6")
■ Double.valueOf("2.14")

▀ There are no isReal or isInteger


functions in java
40
Copyright 2016 by Janson Industries
Prewritten Functions Java
▀ String functions
■ Assuming:
♦ String testString = new String("Goodbye");

■ testString.length() - returns 7
■ testString.substring(3, 5) – returns the
string “db”
■ testString.contains("oo") – returns
Boolean value true
■ testString.contains("OO") – returns
Boolean value false
41
Copyright 2016 by Janson Industries
Prewritten Functions Example
▀ How about creating a dice game
■ Ask user if they want to play
■ If yes, generate 2 random numbers
between 1 and 6 to represent the
user's and computer's dice roll
■ Print out numbers and message
saying who won (who got the higher
number) or if it was a tie
■ Ask the user if they want to play
again
42
Copyright 2016 by Janson Industries
Prewritten Functions Example
▀ What's the algorithm?
Dice game algorithm

▀ Then the XD is created

43
Copyright 2016 by Janson Industries
Prewritten Functions Example
▀ Then an additional requirement is
added to create a function called
getMessage
▀ getMessage will
■ Accept the two dice rolls
■ Generate the correct message
■ Return the message

44
Copyright 2016 by Janson Industries
Prewritten Functions Example
▀ Dice game pseudocode

▀ Generate the Flowgorithm


flowchart
■ Random(6) returns a number
between 0 and 5
♦ So need to add 1 to returned number
to get values of 1 through 6

45
Copyright 2016 by Janson Industries
Dice Game Example

46
Copyright 2016 by Janson Industries
Dice Game Example

Copyright 2016 by Janson Industries 47


Dice Game Example When Run

Copyright 2016 by Janson Industries 48


Dice Game Example Java

Copyright 2016 by Janson Industries 49


Dice Game Example Java

Copyright 2016 by Janson Industries 50


Alternative Documentation
▀ IPO (Input Processing Output) Chart
■ Really a table with text (not a chart)

▀ Three columns
■ First column identifies input
■ Second column describes processing
■ Third column identifies output

51
Copyright 2016 by Janson Industries
IPO Example
▀ Function String getMessage(Integer
uRoll, Integer cRoll)
Input Processing Output
uRoll: Integer String msg msg
cRoll: Integer If (uRoll > cRoll) then msg = "You won"
If (cRoll > uRoll) then msg = "I won"
If (cRoll = uRoll) then msg = "It's a tie"

52
Copyright 2016 by Janson Industries
IPO Example
▀ getTotalWithTax(String zip, Real
total)
■ Calculates a Sales amount including
tax based on the zip code where the
transaction takes places
■ Reads file for the Sales tax
percentage (e.g. .065)

53
Copyright 2016 by Janson Industries
IPO Example Pseudocode
Function Real getTotalWithTax(String zip,
Real total)
Declare Real taxRate, useableTaxRate,
totalWithTax
taxRate = Read TaxFile for zip
useableTaxRate = taxRate + 1
totalWithTax = total * useableTaxRate
Return totalWithTax
End Function

54
Copyright 2016 by Janson Industries
IPO Example
▀ getTotalWithTax(String zip, Real
total)
Input Processing Output

zip: String Real useableTaxRate, totalWithTax, totalWithTax


total: Real totalWithTax
taxRate: Real Read taxRate from TaxFile for zip
useableTaxRate = taxRate + 1
totalWithTax = total * useableTaxRate

▀ Notice that taxRate considered


input even though not a function
argument/parameter 55
Copyright 2016 by Janson Industries
Points to Remember
▀ Functions are methods/modules
that return values

▀ Lots of prewritten functions that


provide commonly used logic

▀ IPO Charts are an alternative


design/documentation tool

56
Copyright 2016 by Janson Industries
Assignments
▀ Non-Graded
■ Chap 6 labs 6.1 - 6.5

▀ Graded
■ Chap 6 lab 6.6

57
Copyright 2016 by Janson Industries

Вам также может понравиться