Functions - PowerPoint PPT Presentation

1 / 37
About This Presentation
Title:

Functions

Description:

Refers to the order in which program commands are executed. Order of control flow ... Commands executed sequentially in order. Control flow when a function is invoked ... – PowerPoint PPT presentation

Number of Views:45
Avg rating:3.0/5.0
Slides: 38
Provided by: scie2
Category:
Tags: functions

less

Transcript and Presenter's Notes

Title: Functions


1
Functions
  • Dorian Miller

2
Announcements
  • Homework 3, check Blackboard
  • Scores and solution posted
  • Program 2
  • Due Tuesday Oct 2, 1159pm EST
  • Tip for most partial credit program that
    executes with tester
  • Program 3 available Wednesday

3
Big picture
  • This week
  • Learn about functions
  • Create your own functions
  • Functions we have used
  • document.write(Show text in web page)
  • alert(Show a dialog window with a message)
  • prompt(Enter your name, )
  • Math.floor(4.5)

4
Simple program analogyFunctions
  • Program Instructions
  • Take bread
  • Get scoop of peanut butter
  • Spread scoop on bread
  • Get scoop of jam
  • Spread scoop on bread
  • Done
  • Function
  • Is a group of commands
  • Example
  • Spread scoop on bread

5
Sandwich Analogy
  • Function is a group of commands
  • Example
  • Spread scoop on bread (peanut butter or jelly)
  • Advantage of function
  • Programmer does not need to know the details of
    function, just get the expected result
  • Reuse existing code, do not need to reinvent the
    wheel
  • Program easy to read (sandwich program only 6
    lines)
  • Change result of function with different
    parameters
  • Spread scoop of jelly or peanut butter

6
Predefined functions
  • Predefined functions
  • Part of JavaScript programming language
  • Functions already used
  • document.write(Show text in web page)
  • alert(Show a dialog window with a message)
  • prompt(Enter your name, )
  • Math.floor(4.5)

7
User defined function
  • Create your own functions (user defined)
  • Customize functionality
  • Banner convert and Guessing Game runs when button
    pushed
  • Example of HTML and JavaScript (abbreviated)
  • lthtmlgt
  • ltbodygt
  • ltscriptgt
  • function startHere()
  • alert(Button pushed)
  • lt/scriptgt
  • ltform name "myForm"gt
  • ltinput type"button" onClickstartHere()"
    value"Submit"gt
  • lt/formgt

8
What is a function?
  • Group of programming statements that we give a
    name
  • Name is the function name
  • Examples of functions Program 1 2
  • Statements usually work together to perform a
    specific task/operation
  • The statements between the

9
Why Use functions?
  • To divide complex programs into manageable pieces
  • Can work on functions separately
  • Abstraction
  • Provide an operation to be performed, example
    alert message
  • alert() hide details of creating dialog message
  • Code Re-use
  • Write a small piece of code that can be used
    (called) multiple times (saves typing)
  • Fix problem in one place, problem fixed everywhere

10
Function declaration
  • Specifies the code that will be executed when the
    method is invoked (or called)
  • function sayHello()
  • body of function
  • Syntax
  • function is a keyword
  • sayHello is function name, any valid identifier
  • Parentheses required ()
  • Curly braces required
  • Body of function is JavaScript commands
  • function body goes between

11
A simple function
  • Example
  • Function body generates a dialog message say
    hello
  • Function name is sayHello
  • function sayHello()
  • alert("say hello")

12
Function execution
  • Function execution
  • Function declaration does not execute code
  • Function executes when invoked
  • Syntax for function invocation
  • Function name and parentheses ()
  • sayHello()
  • Invocation made in the program

13
Complete program with function
  • lthtmlgt
  • lth1gtDemo simple function lt/h1gt
  • ltscriptgt
  • // declare function
  • function sayHello()
  • alert("say hello")
  • // function invocation
  • sayHello()
  • lt/scriptgt
  • lt/htmlgt

14
Control Flow
  • Program control flow
  • Refers to the order in which program commands are
    executed
  • Order of control flow
  • Execution begins with the first statement in
    between the script tags
  • Commands executed sequentially in order
  • Control flow when a function is invoked
  • Flow of control jumps to the function and the
    computer executes its code
  • When complete, the flow of control returns to the
    place where the method was called and the
    computer continues executing code

15
Demonstrate control flow
  • lthtmlgt
  • lth1gtDemo simple function lt/h1gt
  • ltscriptgt
  • // declare function
  • function sayHello() 2. Execute function
  • alert("say hello") 3. body of function
  • 4. function done
  • // function invocation
  • sayHello() 1. start here, invoke function
  • alert(Done) 5. continue where function
    invoked
  • lt/scriptgt
  • lt/htmlgt

16
Convention
  • Structure of program
  • Declare functions, multiple possible
  • Main part of program below functions
  • Example outline
  • ltscriptgt
  • function sayHello() // declare functions
  • function other()
  • var x // main program
  • x 5
  • sayHello()
  • lt/scriptgt

17
Function parameters
  • sayHello()
  • Executes same commands each time
  • Result always the same
  • Parameters
  • Parameters are the values passed to function
  • Parameter is a variable within the function
  • Function result based on parameter values
  • Possible to have zero, one or more parameters
  • Example
  • Alert message depends on string parameter
  • alert(String parameter displayed)

18
Function with parameter
  • Declare a function with one parameter
  • Functions result depends on parameter
  • function sayHello(yourName)
  • alert("say hello yourName )
  • Parameter Syntax
  • yourName between () declares the parameter
  • yourName must be a valid identifier
  • yourName is a variable in the function

19
Demonstrate function with parameter
  • lthtmlgt
  • lth1gtDemo simple function lt/h1gt
  • ltscriptgt
  • // declare function
  • function sayHello(yourName)
  • alert("say hello yourName)
  • // execute functions
  • sayHello(Comp110) 1. generate message with
    Comp110
  • sayHello(Class) 2. generate message with
    Class
  • sayHello(Other ex) 3. generate message with
    Other ex
  • lt/scriptgt
  • lt/htmlgt

20
Multiple parameters
  • Function with multiple parameters
  • Parameter names separated by comma
  • Example displays a dialog with result to xy
  • function multi(x, y)
  • alert(multiply x and y (xy))

21
Demonstrate parameter
  • lthtmlgt
  • lth1gtDemo simple function lt/h1gt
  • ltscriptgt
  • // declare function
  • function multi(x, y)
  • alert(multiply x and y (xy))
  • // execute function
  • var firstNum 5
  • var secondNum 2
  • multi(firstNum, secondNum)
  • lt/scriptgt
  • lt/htmlgt

22
Local variables
  • Local variables
  • Variables declared in a function (beside
    parameter)
  • Example, compute is a local variable
  • // declare function
  • function multi(x, y)
  • var compute xy
  • alert(multiply x and y compute)

23
Exercise
  • Write a function named greater that
  • Takes two parameters, a and b
  • Uses an alert message to display the greater
    number or a message stating numbers are equal
  • Examples of invocation
  • greater(10, 12)
  • greater(10, -10)
  • greater(100, 100)

24
Solution
  • Comparison based on parameters a and b
  • a and b used like variables
  • function greater(a, b)
  • if (a gt b)
  • alert(a)
  • else if (a lt b)
  • alert(b)
  • else
  • alert("Numbers are equal a)

25
Function outcome
  • Two possible outcomes of function
  • Function causes a side effect
  • Write function adds text to web page
  • document.write(Show text in web page)
  • Alert generates a dialog
  • alert(Show a dialog window with a message)
  • Function returns a value
  • Prompt returns users input (after creating
    dialog)
  • prompt(Enter your name, )
  • Floor makes a computation, returns whole number
  • Math.floor(4.5)

26
Function return value
  • function that returns value
  • Function invocation returns value
  • Function result used in an expression
  • Example
  • var input
  • input prompt(Your name, )
  • Result of prompt
  • prompt function returns users answer
  • Return value used in the expression
  • Expression result assigned to variable input

27
Function declaration
  • Function returns value
  • Can only return one value
  • Functions stops after return
  • Return usually last command in function
  • function multi(x, y)
  • var compute xy
  • return compute
  • Syntax
  • return is a keyword

28
Demonstrate return
  • lthtmlgt
  • lth1gtDemo simple function lt/h1gt
  • ltscriptgt
  • // declare function
  • function multi(x, y)
  • return xy
  • // execute function
  • var firstNum 5
  • var secondNum 2
  • var result
  • result multi(firstNum, secondNum)
  • alert(the value of result is result)
  • lt/scriptgt
  • lt/htmlgt
  • Function multiplies x and y
  • Function returns result and assigns it two the
    variable result

29
Exercise
  • Write a function named greater that
  • Takes two parameters, a and b
  • Returns the greater number
  • Returns either number if equal
  • Use only one return statement
  • Examples of invocation
  • greater(10, 12) // returns 12
  • greater(10, -10) // returns 10
  • greater(100, 100) // returns 100

30
Solution
  • Comparison based on parameters a and b
  • a and b used like variables
  • Functions stops after return
  • function greater(a, b)
  • var answer // Store result of function
  • if (a gt b)
  • answer a
  • else if (a lt b)
  • answer b
  • else
  • answer a // could be return b
  • return answer

31
Exercise
  • Apply the greater function
  • Write the main program that sums the results of
    the following functions
  • greater(10, 12) // returns 12
  • greater(10, -10) // returns 10
  • greater(100, 100) // returns 100
  • Total sum is 12 10 100 122

32
Solution
  • Function used as part of expression
  • Return value filled in value of function
  • var sum 0
  • sum sum greater(10, 12) // sum 0 12
  • sum sum greater(10, -10) // sum 12 10
  • sum sum greater(100, 100) // sum 22 100
  • alert("sum greater " sum) // sum 122

33
Function control flow
  • Function executes until end (closing curly brace
    )
  • return statement
  • return stops (terminates) a function early
  • Possible to have multiple return statements

34
Multiple return statements
  • Comparison based on parameters a and b
  • Functions stops after return
  • Eliminate the answer variable
  • function greater(a, b)
  • if (a gt b)
  • return a // function stops here
  • else if (a lt b)
  • return b // function stops here
  • else
  • return a // function stops here

35
Other Example
  • When does the function stop?
  • Alert message displayed only if return true is
    not executed
  • function isEven(n)
  • if (n2 0)
  • return true // function stops here if n is even
  • alert(See this message if n is Odd)
  • If (n21)
  • return false // function stops here if n is odd
  • // end of function, if return were not
    encountered

36
Multiple functions
  • // define functions
  • function multi(x, y)
  • return xy
  • function half(n)
  • return n/2
  • // main program
  • var a 3
  • var b 10
  • var result
  • result multi(a, b)
  • alert("Result is " result)
  • result half(result)
  • alert("Now result is " result)
  • multi(3, 10) returns 30 assign to result
  • Display result is 30
  • half(30) returns 15 assign to result
  • Display Now result is 15

37
  • Parameter passing fill in value
Write a Comment
User Comments (0)
About PowerShow.com