# ch03

```Intro to Programming
&amp; Algorithm Design
Modules
Assg1
Assg2
Assg3
Assg4 Labs
This presentation can be viewed on line at: ch03.IntrotoProg.ppt
1
Objective

Explain
 Modules
 Importance
 Hierarchy
of modularization
charts
 Local
vs. reference vs. global
variables
 Passing
values to a module
2
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
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(&quot;Amount of oil is? &quot;);
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(&quot;The cost of &quot; + order + &quot; gallons of oil is &quot; + cost);
}
}
4
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
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
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
7
Why Modularize?


Not just for repeated code
By breaking program into
separate units, different
programmers can simultaneously
work on the different modules
 Speeds

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:
 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
Pseudo Code Modules



“Module” then the module name
followed by parenthesis
Body contains the indented
statements to be executed
End statement: “End Module”
Body
End
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()
End Module

The pseudo code for the entire
program would be
Module main()
End Module
Display “Joe Customer”
Display “1 Main St.”
Display “Enid, OK 56565”
End Module
11
Good Module Names

Module name standards:
 One
&quot;word&quot; (no spaces)
 Begins with lower case letter
 Use camel casing
 Describes processing
 Followed by parenthesis ()

Good examples
 calcSalesTotal()

 cST(),
calcst, getCA
12
Top Down Design

How do you decide what a
module consists of?
 Break
 Examine
 Continue
be broken down into small

Example: baking a cake
13
Top Down Design

have to do to make a cake
 Ingredient
 Process
preparation
the ingredients
 Assemble
the cake
14
Bottom Up Design


Look at all the individual steps
and group them into logical units
Also called Abstraction
15
Modularization


of a series of individual steps
For instance, Aristotle looked at the
world around him and created
abstract groups
 Collies,
up the group dogs
 Calicos, tabbies, Siamese were cats
 Cats, dogs, horses, etc. were
mammals
 Mammals, birds, reptiles were animals
16
Modularization

Aristotle created these abstract
groups
 Kingdoms
 Phylums
 Species
 Etc.
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.
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
Abstraction

We could then group these
modules into larger groups like
 Ingredient
 Process
preparation
the ingredients
 Assemble
the cake
20
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
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
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
Hierarchy Chart

For a sales transaction, same
thing
and store 1st item and qty
Read and store 2nd item and qty
 :
: : : : : : : :
Retrieve first item price
Multiply qty * price
Etc.
24
Hierarchy Chart
Sale
Capture
Input
Calc
Total
Calc Sale
Total
Produce
Receipt
Calc
Tax
25
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
“26
Modules

1
For instance the following
statements are executed in this
Module main()
order
2
6
Display “Howdy”
Display “See ya”
End Module
3
4
5
Display “Joe Customer”
Display “1 Main St.”
Display “Enid, OK 56565”
End Module

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()
“28
Method Call
main()
Display “Howdy”
Display “Joe
Customer”
Display “1 Main
Street
Display “See ya”
End
Display “Enid OK,
56565”
Return
29
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
SFC Method Call

… then Call from Insert window
31
SFC Method Call

Specify method name (don't have to
specify parenthesis), click OK
32
SFC Method Definition

Right click on circle after STOP,
Edit, Insert, enter Module name
33
SFC Method Definition


created after main FC
34
SFC Method Definition
35
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
Raptor Method Call

Edit Call, specify method name,
click Done, Yes, and Done again
37
Raptor Method Call

New diagram and tab created

38
Raptor Method Call

Run,
Execute to
Completion
39
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
Java Method Call

To invoke the method from within
the java class
 Method
name
 Parenthesis
 Semicolon
41
Java Method Call
Here's the Java solution of the method call
42
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
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
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
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
Local Variables


Because of this, you may have
to pass values/variables to a
called method/module
Example, want new method
♦
Accepts two numbers
♦
♦
Displays the result
47
Method Call Values


When method called data passed
like this
two local variables to hold the data
Declare Integer result
result = a + b
Display result
End Module
48
Method Call Values

Final program
Module main
End Module
Declare Integer result
result = a + b
Display result
End Module
49
Method Call Values

static values
Module main
Declare Integer firstNum, secondNum
Display “Input first number to add”
Input firstNum
Display “Input second number to add”
Input secondNum
End Module
Declare Integer result
result = a + b
Display result
End Module
50
SFC

When inserting the call
symbol, there is an
option for specifying
arguments/values to
be passed
51
SFC

Then when creating
the called module,
specify variables to
hold the passed values
52
SFC

Then insert
statement(s) to the
53
SFC

Voila!
 You
have created a
called module that
accepts values
54
Raptor


No way to pass variables to
modules
Treats all variables as global
variables
I.e.
all methods can access all
variables
 More
55
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{
public static void add(int a, int b){
int result;
result = a + b;
System.out.println(&quot;&quot;);
System.out.println(result);
}
56
Java

Very similar to pseudo code
// This method prompts, gets, and passes two integers to the
}
public static void main(String[] args){
int firstNum, secondNum;
Scanner keyboard = new Scanner(System.in);
System.out.print(&quot;Input first number to add &quot;);
firstNum = keyboard.nextInt();
System.out.print(&quot;Input second number to add &quot;);
secondNum = keyboard.nextInt();
}
57
Java
58
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
Method Call Values

Currently when values assigned
and passed
Main Memory
Module main
Declare Integer firstNum = 2
Declare Integer secondNum = 3
End Module
2
3
Declare Integer result
result = a + b
Display result
End Module
firstNum
2
secondNum
3
a
2
b
3
60
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
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
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
End Module
Module add(Integer Ref a, Integer Ref b)
a=8
b=6
End Module
firstNum
8
secondNum
6
a
b
62
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
Global Variables

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
End Module
Declare Integer result
result = firstNum + secondNum
Display result
End Module
64
Global Variables

 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
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
SFC


Called method
expects no values
global variables
67
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
Raptor

MethodCall2.rap
69
Raptor

When MethodCall2.rap run
70
Raptor
71
Raptor
72
Raptor

If you get this error message
change the Mode to
Intermediate
Click
Mode then Intermediate
73
Java



In java, programs are called
classes
Like a method, classes have a
Global variables are defined
outside of any method
74
Java
75



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

Define main to
 Create
a local string variable called
name
 Prompt
the user for their first name
 Assign
the inputted text to the
variable name
 Call
printName and pass the local
variable name to printName
77

Define printName to
 Accept
a string value and assign it to
 Display
text
 &quot;Hi
 So,
if the user had entered Joe, the
result would be
 Hi
Joe, nice to meet you!
78

Send StringModuleCall.txt to me
([email protected]) as an email
attachment with the topic
C3NGA1
79



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



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
81



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
Lab Assgs

 Chap

 Chap

3 Labs 2.1 through 2.4
3 Lab 2.5
Send work as email
attachment with topic C3Lab
83
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