ch03

advertisement
Intro to Programming
& Algorithm Design
Modules
Assg1
Assg2
Assg3
Assg4 Labs
This presentation can be viewed on line at: ch03.IntrotoProg.ppt
Copyright 2014 by Janson Industries
1
Objective

Explain
 Modules
 Importance
 Hierarchy
of modularization
charts
 Local
vs. reference vs. global
variables
 Passing
values to a module
2
Copyright 2014 by Janson Industries
Modules

Programs are broken up into named
sections called modules
In
Java and many other languages
they are called methods

Most modules are not run
automatically
 They

must be called
In the OilCalc java example, you
created one method called main
Copyright 2014 by Janson Industries
3
//
//
//
//
OilCalc.java
Created by R. Janson on 1/1/2015
Program accepts the amount of oil being purchased by the
user then calculates and displays the total cost of that amount
Java
import java.io.*;
import java.util.Scanner;
public class OilCalc {
public static void main(String[] args) throws IOException {
// Variables defined to hold the input and output values
int order = 0;
double cost = 0;
This is one method
// Create the Scanner object, prompt the user for the amount and save it to order
Scanner keyboard = new Scanner(System.in);
System.out.print("Amount of oil is? ");
order = keyboard.nextInt();
// Calculate the cost based on the amount of oil being purchased
cost = order * 2.99;
// Display the cost of oil being purchased
System.out.println("The cost of " + order + " gallons of oil is " + cost);
}
}
4
Copyright 2014 by Janson Industries
Modules


The only method/module called
automatically when a java program
is run as an application (i.e. java
OilCalc) is the main method
Programs can have many other
modules
 These
can be called from the main or
other methods/modules
Copyright 2014 by Janson Industries
5
Why Modularize?

If a series of steps will be used many
times, best to store separately and
simply call when needed
 The
module is reusable
 Cuts
down on duplicate/repeated code
 Less
coding means
 Less
time to code
 Fewer mistakes
 More efficient programs
 Easier/faster to update
Copyright 2014 by Janson Industries
6
Why Modularize?

In addition, if another program wants
to use that module, you know it
works
 Increases

reliability
For example, calculating sales tax
done many times in many programs
 Separate
module
 Cuts
down on code
 New programs can count on code
 If tax rate changes, only change module
Copyright 2014 by Janson Industries
7
Why Modularize?


Not just for repeated code
By breaking program into
separate units, different
programmers can simultaneously
work on the different modules
 Speeds

Copyright 2014 by Janson Industries
up program delivery
Also, smaller groups of code
easier to understand and test
8
Modules

In pseudocode and flowchart to
define a module you specify the
module’s:
 Header
 Indicates
the start of the module and at a
minimum defines the module name
 Body
 Contains
 End
the statements to be executed
statement
 Indicates
the end of the module
9
Copyright 2014 by Janson Industries
Pseudo Code Modules



Header begins with the word
“Module” then the module name
followed by parenthesis
Body contains the indented
statements to be executed
End statement: “End Module”
Header
Body
End
Copyright 2014 by Janson Industries
Module showCustAddress()
Display “Joe Customer”
Display “1 Main St.”
Display “Enid, OK 56565”
End Module
10
Pseudo Code Modules

Any module can invoke another
module with the call command
Module main()
Call showCustAddress()
End Module

The pseudo code for the entire
program would be
Module main()
Call showCustAddress()
End Module
Module showCustAddress()
Display “Joe Customer”
Display “1 Main St.”
Display “Enid, OK 56565”
End Module
Copyright 2014 by Janson Industries
11
Good Module Names

Module name standards:
 One
"word" (no spaces)
 Begins with lower case letter
 Use camel casing
 Describes processing
 Followed by parenthesis ()

Good examples
 calcSalesTotal()
 getCustAddress()

Bad examples
 cST(),
Copyright 2014 by Janson Industries
calcst, getCA
12
Top Down Design

How do you decide what a
module consists of?
 Break
the program into subtasks
 Examine
each subtask and break
it down into further subtasks
 Continue
until the subtask cannot
be broken down into small
subtasks

Example: baking a cake
13
Copyright 2014 by Janson Industries
Top Down Design

What are the things/tasks you
have to do to make a cake
 Ingredient
 Process
preparation
the ingredients
 Assemble
the cake
14
Copyright 2014 by Janson Industries
Bottom Up Design


Look at all the individual steps
and group them into logical units
Also called Abstraction
15
Copyright 2014 by Janson Industries
Modularization


Abstraction creates larger tasks out
of a series of individual steps
For instance, Aristotle looked at the
world around him and created
abstract groups
 Collies,
dachshunds, poodles made
up the group dogs
 Calicos, tabbies, Siamese were cats
 Cats, dogs, horses, etc. were
mammals
 Mammals, birds, reptiles were animals
Copyright 2014 by Janson Industries
16
Modularization

Aristotle created these abstract
groups
 Kingdoms
 Phylums
 Species
 Etc.
Copyright 2014 by Janson Industries
17
Abstraction Example

Many steps to make a cake
 Check
that you have sufficient
quantity of butter
 If not record how much to buy
 Check that you have sufficient
quantity of eggs
 If not record how much to buy
 Check that you have sufficient
quantity of shortening
 If not record how much to buy
 Etc., etc., etc.
Copyright 2014 by Janson Industries
18
Abstraction

We could create modules
 Prepare
shopping list
 Purchase items
 Retrieve and prep baking tools
 Combine cake ingredients
 Combine icing ingredients
 Bake cake
 Cool cake
 Ice Cake
19
Copyright 2014 by Janson Industries
Abstraction

We could then group these
modules into larger groups like
 Ingredient
 Process
preparation
the ingredients
 Assemble
the cake
20
Copyright 2014 by Janson Industries
Abstraction


How do you show the relationship
between all the modules?
Hierarchy chart
 Shows
many levels of abstraction
 Shows
relationship between
modules
 Does
not show individual process
steps
21
Copyright 2014 by Janson Industries
Hierarchy Chart
Make Cake
Ingredient
Prep()
Generate
List()
Process
Ingredients()
Purchase
Ingredients()
Make Cake
Batter()
Assemble
Cake()
Cool
Cake()
Bake
Cake()
Ice
Cake()
Make
Icing()
22
Copyright 2014 by Janson Industries
Hierarchy Chart



Doesn’t explain everything
Does make icing have to be done
after baking?
Cool cake doesn’t fully describe
what has to be done like:
Invert
cake
Remove cake from pan
Place on cellophane
23
Copyright 2014 by Janson Industries
Hierarchy Chart

For a sales transaction, same
thing
Read
and store 1st item and qty
Read and store 2nd item and qty
 :
: : : : : : : :
Retrieve first item price
Multiply qty * price
Add result to subtotal
Etc.
24
Copyright 2014 by Janson Industries
Hierarchy Chart
Sale
Capture
Input
Calc
Total
Calc Sale
Total
Produce
Receipt
Calc
Tax
25
Copyright 2014 by Janson Industries
Flowcharts

Each module/method has a
separate FC
 FC
starts with module/method name
and “()” in oval shape
 All
(except main) end with text
“Return” in oval
 That’s
because program control returns
back to the next statement after the call
when the called module completes
Copyright 2014 by Janson Industries
“26
Modules

1
For instance the following
statements are executed in this
Module main()
order
2
6
Display “Howdy”
Call showCustAddress()
Display “See ya”
End Module
3
4
5
Module showCustAddress()
Display “Joe Customer”
Display “1 Main St.”
Display “Enid, OK 56565”
End Module

Copyright 2014 by Janson Industries
Notice that when module is
finished the statement after the
Call is executed
“27
Flowcharts

And the following would be
displayed
Howdy
Joe Customer
1 Main St.
Enid, OK 56565
See ya

Module call shown in new symbol
with module/method name in
middle of box followed by
parenthesis
moduleName()
Copyright 2014 by Janson Industries
“28
Method Call
main()
Display “Howdy”
showCustAddress()
showCustAddress()
Display “Joe
Customer”
Display “1 Main
Street
Display “See ya”
End
Display “Enid OK,
56565”
Return
29
Copyright 2014 by Janson Industries
SFC Flowcharts

Creating the main method is
standard
Create
 SFC

new flow chart
puts “”main” text in Start oval
Add I/O symbols and text then
click on circle between, Edit,
Insert…
30
Copyright 2014 by Janson Industries
SFC Method Call

… then Call from Insert window
31
Copyright 2014 by Janson Industries
SFC Method Call

Specify method name (don't have to
specify parenthesis), click OK
32
Copyright 2014 by Janson Industries
SFC Method Definition

Right click on circle after STOP,
Edit, Insert, enter Module name
33
Copyright 2014 by Janson Industries
SFC Method Definition


showCustAddress FC
created after main FC
Simply add symbols
to showCustAddress
34
Copyright 2014 by Janson Industries
SFC Method Definition
35
Copyright 2014 by Janson Industries
Raptor Flowcharts

Creating the main method is
standard
Create
 Raptor

new flow chart
names it “main” in tab
Add output symbols and text then
click on Call symbol and drag
between output symbols
36
Copyright 2014 by Janson Industries
Raptor Method Call

Edit Call, specify method name,
click Done, Yes, and Done again
37
Copyright 2014 by Janson Industries
Raptor Method Call

New diagram and tab created

Add symbols to define
showCustAddress
38
Copyright 2014 by Janson Industries
Raptor Method Call

Run,
Execute to
Completion
39
Copyright 2014 by Janson Industries
Java Method

Create a method outside of the
main method with header that has
 Access
info, return value type,
method name and ()
public static void showCustAddress() { }
 The
keyword void means no value is
returned

Enter method statements inside
braces
40
Copyright 2014 by Janson Industries
Java Method Call

To invoke the method from within
the java class
 Method
name
 Parenthesis
 Semicolon
showCustAddress();
41
Copyright 2014 by Janson Industries
Java Method Call
Here's the Java solution of the method call
42
Copyright 2014 by Janson Industries
Local Variables

When a variable is defined in a
method, it can only be accessed
by statements within that method
 I.e.

it is a local variable
The following is OK
Module main()
Declare String name = “Joe”
Display name
End Module
43
Copyright 2014 by Janson Industries
Local Variables

This is OK
Module main()
Declare String name = “Joe”
Display name
Call showName
End Module
Module showName()
Declare String name = “Sam”
Display name
End Module

A program can have two local
variables with the same name

Because their scopes are separate
44
Copyright 2014 by Janson Industries
Local Variables

This is not OK
Module main()
Declare String name = “Joe”
Display name
Declare String name = “Sam”
Display name
End Module

These two local variables called
name have the same scope

Because their scopes are not
separate this will cause an error
when compiled
45
Copyright 2014 by Janson Industries
Local Variables

This is not OK
Module main()
Declare String name = “Joe”
Call showName
End Module
Module showName()
Display name
End Module

Because name is defined in
main() it cannot be accessed in
showName()
 It
scope is the main method
46
Copyright 2014 by Janson Industries
Local Variables


Because of this, you may have
to pass values/variables to a
called method/module
Example, want new method
named add that
♦
Accepts two numbers
♦
Adds the two numbers
♦
Displays the result
47
Copyright 2014 by Janson Industries
Method Call Values


When method called data passed
like this
Call add(2, 3)
In add method header must define
two local variables to hold the data
Module add(Integer a, Integer b)
Declare Integer result
result = a + b
Display result
End Module
48
Copyright 2014 by Janson Industries
Method Call Values

Final program
Module main
Call add(2, 3)
End Module
Module add(Integer a, Integer b)
Declare Integer result
result = a + b
Display result
End Module
49
Copyright 2014 by Janson Industries
Method Call Values

Can pass variables instead of
static values
Module main
Declare Integer firstNum, secondNum
Display “Input first number to add”
Input firstNum
Display “Input second number to add”
Input secondNum
Call add(firstNum, secondNum)
End Module
Module add(Integer a, Integer b)
Declare Integer result
result = a + b
Display result
End Module
Copyright 2014 by Janson Industries
50
SFC

When inserting the call
symbol, there is an
option for specifying
arguments/values to
be passed
51
Copyright 2014 by Janson Industries
SFC

Then when creating
the called module,
specify variables to
hold the passed values
52
Copyright 2014 by Janson Industries
SFC

Then insert
statement(s) to the
new module (add)
53
Copyright 2014 by Janson Industries
SFC

Voila!
 You
have created a
called module that
accepts values
54
Copyright 2014 by Janson Industries
Raptor


No way to pass variables to
modules
Treats all variables as global
variables
I.e.
all methods can access all
variables
 More
about this later
55
Copyright 2014 by Janson Industries
Java

Very similar to pseudo code
// MethodCall1.java
// R. Janson 1/3/2015
// This pgm calls a method and passes two integers
import java.io.*;
import java.util.Scanner;
public class MethodCall1{
// This method receives two ints, adds them and displays them
public static void add(int a, int b){
int result;
result = a + b;
System.out.println("");
System.out.println(result);
}
56
Copyright 2014 by Janson Industries
Java

Very similar to pseudo code
// This method prompts, gets, and passes two integers to the
// add method
}
public static void main(String[] args){
int firstNum, secondNum;
Scanner keyboard = new Scanner(System.in);
System.out.print("Input first number to add ");
firstNum = keyboard.nextInt();
System.out.print("Input second number to add ");
secondNum = keyboard.nextInt();
add(firstNum, secondNum);
}
57
Copyright 2014 by Janson Industries
Java
58
Copyright 2014 by Janson Industries
Method Call Values

Problem: multiple local variables
with the same values
 firstNum
and a
 secondNum
and b

Takes up extra memory space

A couple ways around this
 Reference
 Global
variables
variables
59
Copyright 2014 by Janson Industries
Method Call Values

Currently when values assigned
and passed
Main Memory
Module main
Declare Integer firstNum = 2
Declare Integer secondNum = 3
Call add(firstNum, secondNum)
End Module
2
3
Module add(Integer a, Integer b)
Declare Integer result
result = a + b
Display result
End Module
firstNum
2
secondNum
3
a
2
b
3
60
Copyright 2014 by Janson Industries
Reference Variables

Don’t hold a value, simply reference
(point to) another value
Main Memory
Module main
Declare Integer firstNum = 2
Declare Integer secondNum = 3
Call add(firstNum, secondNum)
End Module
Module add(Integer Ref a, Integer Ref b)
Declare Integer result
result = a + b
Display result
End Module
firstNum
2
secondNum
3
a
b
61
Copyright 2014 by Janson Industries
Reference Variables

Changes to the reference variables
change the original variable’s values
Main Memory
Module main
Declare Integer firstNum = 2
Declare Integer secondNum = 3
Call add(firstNum, secondNum)
End Module
Module add(Integer Ref a, Integer Ref b)
a=8
b=6
End Module
firstNum
8
secondNum
6
a
b
62
Copyright 2014 by Janson Industries
Global Variables

Accessible to all modules within
the program
i.e.
It’s scope is global (program
wide) not local (module wide)

Defined at the beginning of the
program before any module
definition
63
Copyright 2014 by Janson Industries
Global Variables

Advantages: less code, fewer
variables, no need to pass vars
Declare Integer firstNum, secondNum
Module main
Display “Input first number to add”
Input firstNum
Display “Input second number to add”
Input secondNum
Call add()
End Module
Module add()
Declare Integer result
result = firstNum + secondNum
Display result
End Module
Copyright 2014 by Janson Industries
64
Global Variables

Disadvantages:
 Since
any method can access,
harder to find errors with that global
variable's value
 Makes
the module less
independent/self-contained
 I.e.
it needs the global variable to work
65
Copyright 2014 by Janson Industries
SFC



No easy way to
show global
variables
In main module,
simply put a
comment that says
they are global
Change call so no
values passed
66
Copyright 2014 by Janson Industries
SFC


Called method
expects no values
add() uses the
global variables
67
Copyright 2014 by Janson Industries
Raptor

Treats all variables as global
variables
 No
ability to pass values to called
modules

When variable defined in
module it’s has a global scope
68
Copyright 2014 by Janson Industries
Raptor

MethodCall2.rap
69
Copyright 2014 by Janson Industries
Raptor

When MethodCall2.rap run
70
Copyright 2014 by Janson Industries
Raptor
71
Copyright 2014 by Janson Industries
Raptor
72
Copyright 2014 by Janson Industries
Raptor

If you get this error message
change the Mode to
Intermediate
Click
Mode then Intermediate
73
Copyright 2014 by Janson Industries
Java



In java, programs are called
classes
Like a method, classes have a
header
Global variables are defined
after the class header but
outside of any method
74
Copyright 2014 by Janson Industries
Java
75
Copyright 2014 by Janson Industries
Method Call Non-Graded Assg1



Create pseudocode for a
program called stringModuleCall
Save the pseudo code in a text
file named StringModuleCall.txt
Define stringModuleCall to have
two modules called
 main()
 printName()
76
Copyright 2014 by Janson Industries
Method Call Non-Graded Assg1

Define main to
 Create
a local string variable called
name
 Prompt
the user for their first name
 “Please
enter your first name”
 Assign
the inputted text to the
variable name
 Call
printName and pass the local
variable name to printName
77
Copyright 2014 by Janson Industries
Method Call Non-Graded Assg1

Define printName to
 Accept
a string value and assign it to
a local variable called userName
 Display
userName with the following
text
 "Hi
userName, nice to meet you!"
 So,
if the user had entered Joe, the
result would be
 Hi
Joe, nice to meet you!
78
Copyright 2014 by Janson Industries
Method Call Non-Graded Assg1

Send StringModuleCall.txt to me
(rjanson@fscj.edu) as an email
attachment with the topic
C3NGA1
79
Copyright 2014 by Janson Industries
Method Call Non-Graded Assg2



Based on the pseudo code in
StringModuleCall.txt create an
SFC flowchart
Store the flowchart in a file
called StringModuleCall.sfc
Email the flowchart as an
attachment with the topic of
C3NGA2
80
Copyright 2014 by Janson Industries
Method Call Non-Graded Assg3



Based on the pseudo code in
StringModuleCall.txt and the
SFC flowchart create a Raptor
flowchart
Store the flowchart in a file
called StringModuleCall.rap
Email the flowchart as an
attachment with the topic of
C3NGA3
Copyright 2014 by Janson Industries
81
Method Call Non-Graded Assg4



Based on the pseudo code
and the flowcharts, create a
java program to perform the
same function
Store the java code in a file
called StringModuleCall.java
Email the java file as an
attachment with the topic of
C3NGA4
82
Copyright 2014 by Janson Industries
Lab Assgs

Non-graded
 Chap

Graded
 Chap

3 Labs 2.1 through 2.4
3 Lab 2.5
Send work as email
attachment with topic C3Lab
83
Copyright 2014 by Janson Industries
Points to Remember

Breaking programs into modules is
good design because it results in
code reuse
 Decreases
program size
 Decreases
program complexity
 Decreases
cost of program
development
 Decreases
cost of modifying a program
84
Copyright 2014 by Janson Industries
Download