BIL106E - PowerPoint PPT Presentation

1 / 64
About This Presentation
Title:

BIL106E

Description:

BIL106E – PowerPoint PPT presentation

Number of Views:26
Avg rating:3.0/5.0
Slides: 65
Provided by: insIt6
Category:

less

Transcript and Presenter's Notes

Title: BIL106E


1
BIL106E
  • Procedural PROGRAMMING
  • Functions Subroutines
  • Modules

2
Contents
  • PRELUDE
  • PROGRAM MODULE CONCEPTS
  • THE PROCEDURE CONCEPT
  • FUNCTIONS
  • SUBROUTINES
  • ACTUAL DUMMY ARGUMENTS
  • LOCAL GLOBAL OBJECTS
  • INITIAL VALUES

3
Prelude
  • From problem to program in three basic steps
  • 1) Specify the problem clearly
  • 2) Analyse the problem and break it down into
    its fundamental elements.
  • 3) Code the program according to the plan
    developed at step 2.
  • Additionally there is also a 4.th step
  • 4) Test the program exhaustively, and repeat
    steps 2 and 3 as necessary.

4
Prelude
  • Golden rules of programming
  • Always plan ahead
  • Develop in stages
  • Modularize
  • Keep it simple (KISS)
  • Test throughly
  • Document all programs
  • Enjoy your programming

"Devide and concure"
5
Prelude
  • Time rates for development process of softwares
  • Design 30
  • Coding 30
  • Testing Debuging 40

6
  • PRELUDE
  • THE PROCEDURE CONCEPT
  • PROGRAM MODULE CONCEPTS
  • FUNCTIONS
  • SUBROUTINES
  • ACTUAL DUMMY ARGUMENTS
  • LOCAL GLOBAL OBJECTS
  • INITIAL VALUES

7
The Precedure Concept
  • It is often appropriate to subdivide a
    computational task-especially large one- into
    subtasks that can be developed and analysed
    independently.
  • The overall task may be organised as a set of
    procedures that implement the subtasks.
  • Each procedure is defined by an independent
    group of statements called a subprogram.
  • This process of subdivision is called procedural
    refinement. For instance, you can organise a
    data processing task with separate procedures for
    input, computation, and output.

8
The Procedure Concept
Main program
  • Miles,
  • I thought we might have Rasberry Chicken tonight
    (see page 87 of the Silver Palate Cookbook). I'll
    be a bit late home, so could you make a start
    please ?

Procedure call
Module
Procedure
9
Example In F
  • !cookbook.f
  • program aNote
  • use cookbook
  • print , "Miles,"
  • print , " I thought we might have Rasberry
    Chicken tonight"
  • print , "Here is the recipe"
  • print , display_rasberry( )
  • print , "I will be a bit late home, so could you
    make a start please?"
  • end program aNote

10
Example In F
  • Open a new window in F_World and write
  • !cookbookM.f
  • module cookbook
  • public display_rasberry
  • contains
  • function display_rasberry( ) result(recipe)
  • character (len100) recipe
  • recipe "RASBERRY CHICKEN Boneless chicken
    breasts are quick and econmical to serve but
    often dull to eat..."
  • end function display_rasberry
  • end module cookbook

Local variable
11
Program output
  • One moment ... . . . . . . . . . .
    . . .
  • ...
  • Imagine1 F Processor Running 'CookBookMain'...
  • Miles,
  • I thought we might have Rasberry Chicken
    tonight
  • Here is the recipe
  • RASBERRY CHICKEN Boneless chicken breasts are
    quick and econmical to serve but often dull to
    eat
  • I will be a bit late home, so could you make a
    start please?
  • Program completed.
  • Press Enter to continue.

12
Advantages
  • Reduces duplication
  • Modification is easy
  • Reduces volume of code
  • Independent development
  • One team/person works on main part, other
    team(s)/person works on procedure(s)
  • Organized/Tidy/Structured code

13
Where may a procedure be called from?
  • A procedure (subprogram) may be called from
  • the main program
  • another subroutine subprogram
  • another function
  • Note Functions may be called by itself
    (recursive procedure, recursion) under special
    conditions.See Ellis' book chapter 8.1, p 194.

14
Types of Procedures
  • Procedures - origin
  • Intrinsic (built-in, comes with F )
  • sin(x), cos(x), abs(x),
  • "Write your own" (homemade)
  • Written by someone else (libraries)
  • Procedures (subprograms) form
  • Functions can be assigned to a variable
  • Subroutines can NOT be assigned to a variable

15
Self Study
  • Ellis's Book Example 4.1, p 74
  • Intrinsic functions in Appendix A, p 591-600
  • Download builtIn.f from class web site, run the
    code, modify as you wish.

16
  • PRELUDE
  • THE PROCEDURE CONCEPT
  • PROGRAM MODULE CONCEPTS
  • FUNCTIONS
  • SUBROUTINES
  • ACTUAL DUMMY ARGUMENTS
  • LOCAL GLOBAL OBJECTS
  • INITIAL VALUES

17
Program Module Concepts
  • Main Program A sequence of statements starting
    with a program and ending with an end program
    statement is known as a main program or main
    program unit.
  • Module is a means of collecting a set of related
    objects (procedures, variables, data types) and
    making them available to a program in an
    controlled manner.

18
Program Module Concepts
  • Main program
  • program name
  • use statements
  • .
  • .
  • specification statms.
  • .
  • executable statms.
  • .
  • end program name
  • Module program
  • module nameM
  • use statementsM
  • .
  • .
  • specification statms.
  • .
  • .
  • .
  • end module nameM
  • Module program unit containing proc. definitions
  • module nameM2
  • use statementsM2
  • .
  • specification statms.
  • .
  • .
  • .
  • contains
  • procedure defin.s
  • .
  • end module nameM2

19
Demonstration
  • !Main Program
  • program simple
  • use myModule
  • integer i
  • i myFonk( )
  • call mySub( )
  • end program simple
  • ! Module
  • module myModule
  • public myFonk
  • public mySub
  • contains
  • function myFonk( ) result(a)
  • integer a
  • print , "Hello from myFonk"
  • a10
  • end function myFonk
  • subroutine mySub( )
  • print , "Hello from mySub"
  • end subroutine mySub
  • end module myModule

20
Module Syntax
Specification statements
  • !AModule.f
  • module ModuleName
  • public list of names !declaration of exported
    procedures from the module
  • contains
  • function name(arg1, arg2) result (res_val)
  • use other module names
  • type, intent (in) arg1, arg2 ! dummy
    argument declaration
  • type res_val ! result
    variable declaration
  • type local_val ! local variable
    declarations
  • !following statements can NOT be accessed from
    outside
  • ...
  • statements
  • ...
  • end function name
  • ...
  • end module ModuleName

procedure definitions
21
  • PRELUDE
  • THE PROCEDURE CONCEPT
  • PROGRAM MODULE CONCEPTS
  • FUNCTIONS
  • SUBROUTINES
  • ACTUAL DUMMY ARGUMENTS
  • LOCAL GLOBAL OBJECTS
  • INITIAL VALUES

22
Functions
  • A function is given information to operate on by
    means of one or more arguments and delivers a
    single result.
  • function name (d1,d2,..) result (result_name)
  • ..LOCAL statements
  • end function name
  • d1,d2 are dummy arguments representing the actual
    arguments.
  • result_name is the name of a variable which will
    be used to store the result of the function.

23
Function Example
  • function cube_root (x) result (root)
  • ! A function to calculate the cube root of a
    positive
  • ! real number
  • real, intent (in) x ! dummy argument
    declaration
  • real root ! result variable
    declaration
  • real log_x ! local variable
    declaration
  • log_xlog(x) ! can NOT be accessed
    from outside
  • rootexp(log_x/3.0)
  • end function cube_root

Local variables
24
Explanation
  • Internal variables or local variables
  • log_x root are not accessible from outside the
    function
  • Result variable
  • "root" is the result variable appears in
    "result" statement. Every fn. must have only 1
    result variable.
  • Decleration of the dummy arguments
  • real, intent (in) x
  • The dummy argument x can not be changed by the
    function cube_root.
  • end function
  • It causes execution of the program to return to
    the point in the calling program.

25
Use of Functions
  • Its main purpose is to calculate single value
    based on its arguments
  • The operation of a function should be
    predictable. Do not (can not be ) alter(ed) the
    arguments
  • It is not permitted to call a subroutine in
    anyway
  • Use print and read statements for only diagnostic
    (debuging) purpose.

26
Use of Functions
  • A function may appear anywhere that an expression
    may appear.
  • RHS of an assignment statmn, a b
    sin(x)
  • in a output list, print , sin(x)
  • as a argument in another procedure, c a
    myFunction( b, sin(x) ) call mySubroutine(
    b, sin(x) )

27
Working example module prog.
  • !cubeRootM.f
  • module cubeRootM
  • public cube_root !declaration of exported
    procedures from the module
  • contains
  • function cube_root (x) result (root)
  • ! A function to calculate the cube root of a
    positive
  • ! real number
  • real, intent (in) x ! dummy argument
    declaration
  • real root ! result variable
    declaration
  • real a ! local variable declaration
  • alog(x) ! can NOT be accessed (used)
    from outside
  • rootexp(a/3.0)
  • end function cube_root
  • end module cubeRootM

Validate every module after completion by
clicking "validate module"
28
Working example main prog
  • ! CubeRoot.f
  • program CubeRoot
  • use cubeRootM
  • real a, sonuc
  • print , "input a positive real"
  • read , a
  • print , "The cube root of ", a, " is "
  • sonuc cube_root(a) !this a is different from
    the
  • print , sonuc !a defined in the
    function.
  • end program CubeRoot

"Run program"
29
  • PRELUDE
  • THE PROCEDURE CONCEPT
  • PROGRAM MODULE CONCEPTS
  • FUNCTIONS
  • SUBROUTINES
  • ACTUAL DUMMY ARGUMENTS
  • LOCAL GLOBAL OBJECTS
  • INITIAL VALUES

30
Subroutines
  • Arguments of a subroutine are used both to
    receive information to operate on and to return
    results.
  • A subroutine is accessed by means of a "call"
    statement which gives the name of the subroutine
    and a list of arguments which will be used to
    transmit information between the calling program
    unit and subroutine.
  • call name (arg1,arg2,)
  • Unlike a function, the values are returned by
    means of one or more of its arguments.
  • A subroutine is a standalone statement. It can
    not be appear in any part of an expression.

31
Example module prog.
  • Write a subroutine, roots, which calculates the
    square root, the cube root, the fourth root and
    the fifth root of a positive real number.
  • !rootsM.f
  • module example_module
  • public roots
  • contains
  • subroutine roots (x,square_root,cube_root,fourth_r
    oot,fifth_root)
  • real, intent(in) x
  • real, intent(out) square_root,cube_root,
  • fourth_root,fifth_root
  • real log_x
  • square_rootsqrt(x)
  • log_xlog(x)
  • cube_rootexp(log_x/3.0)
  • fourth_rootexp(log_x/4.0)
  • fifth_rootexp(log_x/5.0)
  • end subroutine roots
  • end module example_module

32
Example main prog.
  • !RootsMain.f
  • program rootsMain
  • use example_module
  • real pos_num,root_2,root_3,root_4,root_5
  • print ,"Please type a positive real number"
  • read ,pos_num
  • call roots (pos_num,root_2,root_3,root_4,root_5)
  • print ,"The square root of",pos_num,"is",root_2
  • print ,"The cube root of",pos_num,"is",root_3
  • print ,"The fourth root of",pos_num,"is",root_4
  • print ,"The fifth root of",pos_num,"is",root_5
  • end program rootsMain

33
A note
  • If a subroutine has no arguments, then its
    initial statement takes the form
  • subroutine sub ()
  • call sub ()

34
  • PRELUDE
  • THE PROCEDURE CONCEPT
  • PROGRAM MODULE CONCEPTS
  • FUNCTIONS
  • SUBROUTINES
  • ACTUAL DUMMY ARGUMENTS
  • LOCAL GLOBAL OBJECTS
  • INITIAL VALUES

35
Actual dummy arguments
  • call sub (a,c,d) ? a,c,d are the actual
    arguments.
  • subroutine sub (x,y,z) ? x,y,z are the dummy
    arguments.
  • The order and types of the actual arguments must
    correspond exactly with the order and types of
    the corresponding dummy arguments.
  • The intent attribute must be used to control
    the direction in which arguments are used to pass
    information.

36
Intent attribute
  • intent (in) dummy argument provides information
    to procedure and it is not be altered by
    procedure
  • intent (out) dummy argument returns information
    from the procedure to the calling program.
  • Intent (inout) dummy argument may be used for
    transmission of information in both directions.
  • A functions dummy arguments must all have
    intent(in).
  • A Subroutines arguments may have any of the
    three forms of intent attribute.

37
Example
  • ...
  • real a,c,b,d
  • a1 b2 c3 d4 (Not real code)
  • ! an expression is not allowed at out or inout
    types
  • call mySub(a1, bb, c, d)
  • print , "1.arg-gt a1 1.arg-gt bb"
  • print , "arg3 arg1 arg2"
  • print , "arg4 arg4 arg1"
  • print , "After calling mySub"
  • print , "a", a, " b",b, " c", c," d", d
  • ...

... subroutine mySub(arg1, arg2, arg3,
arg4) real, intent(in) arg1, arg2 real,
intent(out) arg3 real, intent(inout) arg4 !
the following is an error !arg1 33 ! the
following is a error !arg2 565 arg3 arg1
arg2 arg4 arg4 arg1 ...
Please find the programs at the web site of the
course Main program ArgTypes.f, Module
ArgTypesM.f
38
Output
  • One moment ... . . . . . . . . . .
    . . .
  • F Version ...
  • Imagine1 F Processor Running 'argTypes'...
  • Before calling mySub
  • a 1.000000 b 2.000000 c 3.000000
    d 4.000000
  • 1.arg-gt a1 1.arg-gt bb
  • arg3 arg1 arg2
  • arg4 arg4 arg1
  • After calling mySub
  • a 1.000000 b 2.000000 c 6.000000
    d 6.000000
  • Program completed.
  • Press Enter to continue.

39
Assumed length character declaration
  • A character dummy argument must be declared with
    an assumed length that is (len).
  • character (len) , intent(in) name
  • Assumed length character declaration can only be
    used for declaring a dummy argument and involves
    replacing the length specifier by an asterisk.

40
Example Ellis' Ex. 4.2, p 86Main program
  • !IntentMain.f
  • program IntentMain
  • use intentModule
  • character (len20) firstName, lastName,
    fullName
  • print , "First Name "
  • read , firstName
  • print , "Last Name "
  • read , lastName
  • call getFullName( firstName, lastName, fullName )
  • print , "Full Name ", fullName
  • end program IntentMain

41
Example Ellis' Ex. 4.2, p 86Module program
  • !IntentM.f
  • module intentModule
  • public getFullName
  • contains
  • subroutine getFullName( fName, lName, full_name )
  • character (len), intent(in) fName, lName
  • character (len), intent(out) full_name
  • !use adjustl to remove redundant leading blanks
  • !use trim to remove redundant blanks at the end
    of fName
  • full_name trim( adjustl( fName )) // " " //
  • adjustl( lName )
  • end subroutine getFullName
  • end module intentModule

42
  • PRELUDE
  • THE PROCEDURE CONCEPT
  • PROGRAM MODULE CONCEPTS
  • FUNCTIONS
  • SUBROUTINES
  • ACTUAL DUMMY ARGUMENTS
  • LOCAL GLOBAL OBJECTS
  • INITIAL VALUES

43
Local global objects
  • ? OOP Data Hiding/Encapsulation
  • All the variables defined in a procedure is known
    by the procedure in which they are defined.
    Unless they are declared (as public) at the
    declaration part of the module, they can not be
    accessed from external parts of the code.
  • A variable ( or an object) can be made accessible
    from all procedures only within its module, but
    not from the other modules by declaring it as
    private at the module's specification part

44
Example1
  • module natural_constantsreal, parameter, public
    pi3.1415, e2.718integer, public
    counterend module natural_constants
  • subroutine module_example (arg1,arg2)use natural
    constants.end subroutine module_example

45
Example2
  • module example
  • public sub1,sub2
  • real, parameter, public pi3.1415, e2.718
  • real, public global_var1, global_var2
  • contains
  • subroutine sub1 (a,b,c)
  • use example
  • cpiab
  • end subroutine sub1
  • subroutine sub2 (x,y,z)
  • use example
  • global_var1xglobal_var2
  • end subroutine sub2
  • end module example

They are available to all modules in which use
examplespecification statement is declared
46
  • module example
  • public sub1,sub2
  • real, parameter, public pi3.1415, e2.718
  • real, public global_var1, global_var2
  • contains
  • subroutine sub1 (a,b,c)
  • use example
  • cpiab
  • end subroutine sub1
  • subroutine sub2 (x,y,z)
  • use example
  • global_var1xglobal_var2
  • end subroutine sub2
  • end module example

47
private attribute
  • If it is not required to access the constants or
    variables outside the module the public attribute
    may be replaced by private.real, parameter,
    private pi3.1415, e2.718real, private
    global_var1,global_var2
  • In this case the entities within the module will
    not be accessible from outside.
  • A private statement must appear after any use
    statements but before any other statements.
  • module another_module
  • use natural_constants
  • private
  • real, parameter, public pi_by_two0.5pi
  • .
  • end module another_module

48
module natural_constantsreal, parameter, public
pi3.1415, e2.718real aReal integer,
public counterinteger, private
meaningless end module natural_constants
program aMainPrg use aModule use
natural_constantsaReal pi e 28.0 counter
counter 1 end program aMainPrg
module aModule contains subroutine mySub() use
natural_constantsaReal pi counter 1 end
program aMainPrg
49
Example
  • LocGlob.f, LocGlobM.f LocGlobM2.f
  • Load all
  • Validate LocGlobM.f , LocGlobM2.f respectively
  • Run LocGlob.f

50
  • PRELUDE
  • THE PROCEDURE CONCEPT
  • PROGRAM MODULE CONCEPTS
  • FUNCTIONS
  • SUBROUTINES
  • ACTUAL DUMMY ARGUMENTS
  • LOCAL GLOBAL OBJECTS
  • INITIAL VALUES

51
save attribute (static var.)
  • The values of procedures local variables may be
    retained between successive references (calls) to
    the procedures by using the save attribute.
  • real, save list of real variables
  • Only local objects are allowed.
  • It is not possible to give the save attribute to
    a dummy argument or a result variable.
  • It is not permissible to specify the save
    attribute for any variables declared in the main
    program.

52
Initial values
  • Local variables in a procedure may be given an
    initial value as a part of their declaration as
    long as they have save attribute.
  • It is not possible to use this form of
    initialization in the main program since the save
    attribute can only be used with local variables
    in a subroutine or function.
  • real, save a,b1.23,c
  • integer, save count0

53
Example
  • subroutine new_page()
  • !this sub. prints a heading and the page number
  • ! at the top of the next page.
  • integer , save page 0 ! local variable
  • !update the page number and print heading
  • page page 1
  • print , "Example page heading. Page ", page
  • end subroutine new_page
  • The page number is initialized to zero at the
    time of the first entry to the subroutine.
  • But on each entry thereafter it has the same
    value that it had on exit the previous time.
    Since its value is increased by one each time the
    subroutine is entered, this has the desired
    effect.

54
Example
  • !saveEgMain.f
  • program saveEgMain
  • use saveEg
  • do i1,10
  • call new_page()
  • end do
  • end program saveEgMain

  • !saveEg.f
  • module saveEg
  • public new_page
  • contains
  • subroutine new_page()
  • !this sub. prints a heading and the page
  • !number at the top of the next page.
  • integer , save page 0 ! static local
    variable
  • !update the page number and print heading
  • page page 1
  • print , "Example page heading. Page ", page

55
Result
  • Example page heading. Page 1
  • Example page heading. Page 2
  • Example page heading. Page 3
  • Example page heading. Page 4
  • Example page heading. Page 5
  • Example page heading. Page 6
  • Example page heading. Page 7
  • Example page heading. Page 8
  • Example page heading. Page 9
  • Example page heading. Page 10

56
Step by step calc
  • 1.step i1
  • call new_page( )
  • page 0 ! Initialization of the static variable
    integer , save page 0
  • page 0 1
  • print , "Example page heading. Page ", 1
  • 2.step i2
  • call new_page( )
  • page 1 1
  • print , "Example page heading. Page ", 2
  • 3.step i2
  • call new_page( )
  • page 2 1
  • print , "Example page heading. Page ", 3
  • ...

57
Reading assignment
  • Ellis's book chapter 4

58
Homework4
  • Ellis's Book page 101. programming exercise 4.9
  • Due Date 13/03/2003

59
Resursive Procedures
  • A procedure which call itself is called resursive
    procedure.
  • Syntax in F
  • Recursive Functionrecursive function
    aFunName(..args list..) result(val)
  • Recursive Subroutinerecursive subroutine
    aSub(..arg list..)

60
Resursive Procedures
  • In general, a function is said to be defined
    recursively if its definition consists of two
    parts
  • An anchor or base case, in which the value of the
    function is specified for one or more values of
    the argument(s).
  • An inductive or recursive step, in which the
    functions value for the current value of the
    argument(s) is defined in terms of previously
    defined function values and/or argument values.
  • Examples
  • 1) The factorial function is computed by
  • 0! 1 (The anchor or base case)
  • For ngt0, n! n(n-1)! (The inductive or
    recursive step)
  • 2) The power function is computed by
  • x0 1 (The anchor or base case)
  • For ngt0, xn xxn-1 (The inductive or
    recursive step)

61
Factorial Example
  • resursive function factorial (n)
    result(factorial_n)
  • integer , intent(in) n
  • real factorial_n
  • select case (n)
  • case (0)
  • factorial_n 0 !thats the end
  • case (1)
  • factorial_n n factorial_n( n-1 )
    !recursive part
  • case default
  • factorial_n 0.0 !if n is negative return
    zero...
  • end function factorial

62
Step by step calc
  • Lets n 4
  • 1.step factorial(4)n4 ? case(1)factorial_n
    4 factorial( 3 ) ? refer factorial func with
    arg val 3
  • 2. step factorial( 3 ) n3 ? case(1)factorial_
    n 3 factorial( 2 ) ? refer factorial func
    with arg val 2
  • 3. step factorial( 2 ) n2 ? case(1)factorial_
    n 2 factorial( 1 ) ? refer factorial func
    with arg val 1
  • 4. step factorial( 1 ) n1 ? case(1)factorial_
    n 1 factorial( 0 ) ? refer factorial func
    with arg val 0
  • 5. step factorial( 0 ) n0 ? case( 0
    )factorial_n 1 ? NO MORE REFERENCE TO
    factorial(n).END REACHED. START TO CALCULATE IN
    REVERSE ORDER.

? 24
63
Self study
  • Ellis' book Section 8.1
  • Write and run the subroutine version of the
    factorial program with "if" instead of "case"
  • Do the step by step calculation by writing on the
    paper.

64
Location of Procedures
  • This function subprogram can be made accessible
    to a program, called the main program, in three
    ways
  • It is placed in a subprogram section in the main
    program just before the end program statement in
    this case it is called an internal subprogram.
  • It is placed in a module from which it can be
    imported into the program in this case, it is
    called a module subprogram.
  • It is placed after the end program statement of
    the main program, in which case it is called an
    external subprogram.

65
Internal subprogram
  • Internal subprograms are placed in a subprogram
    section at the end of the main program (or at the
    end of an external subprogram).
  • The program unit (main program or subprogram)
    that contains an internal subprogram is called a
    host for that subprogram.
  • This subprogram section has the form
  • contains
  • subprogram_1
  • subprogram_2 ...
  • subprogram_n
  • where each subprogram_i does not contain a
    subprogram section.
  • ! Following example illustrates the use of an
    internal subprogram.

66
Example
  • !InternalProcedure.f
  • program InternalProcedure
  • implicit none
  • print , "Fun1 " , fun1()
  • contains
  • function fun1() result(a)
  • integer year ! local to fun1()
  • year 1773
  • end function fun1
  • end program InternalProcedure
  • NOTE THIS TYPE IS NOT VALID in F_WORLD

67
Application
  • Write a subroutine which calculates the factorial
    value of a given number without using resursive
    function.
  • Write a main program to call above subroutine.
    Print both input and output.
  • Modify your code
  • Eg. Convert the subroutine to a function
Write a Comment
User Comments (0)
About PowerShow.com