Download ch03

Document related concepts
no text concepts found
Transcript
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
n
Explain
u
Modules
u
Importance of modularization
u
Hierarchy charts
u
Local vs. reference vs. global
variables
u
Passing values to a module
2
Copyright 2014 by Janson Industries
Modules
n
Programs are broken up into
named sections called modules
u
n
Most modules are not run
automatically
u
n
Copyright 2014 by Janson Industries
In Java and many other languages
they are called methods
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("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
n
n
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
u
Copyright 2014 by Janson Industries
These can be called from the main or
other methods/modules
5
Why Modularize?
n
If a series of steps will be used many
times, best to store separately and
simply call when needed
u
The module is reusable
u
Cuts down on duplicate/repeated code
u
Less coding means
F
F
F
F
Copyright 2014 by Janson Industries
Less time to code
Fewer mistakes
More efficient programs
Easier/faster to update
6
Why Modularize?
n
In addition, if another program wants
to use that module, you know it
works
u
n
Increases reliability
For example, calculating sales tax
done many times in many programs
u
Separate module
F
F
F
Copyright 2014 by Janson Industries
Cuts down on code
New programs can count on code
If tax rate changes, only change module
7
Why Modularize?
n
n
Not just for repeated code
By breaking program into
separate units, different
programmers can simultaneously
work on the different modules
u
n
Copyright 2014 by Janson Industries
Speeds up program delivery
Also, smaller groups of code
easier to understand and test
8
Modules
n
In pseudocode and flowchart to
define a module you specify the
module’s:
u
Header
F
u
Body
F
u
Indicates the start of the module and at a
minimum defines the module name
Contains the statements to be executed
End statement
F
Indicates the end of the module
9
Copyright 2014 by Janson Industries
Pseudocode 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 pseudocode 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(), calcst, getCA
Copyright 2014 by Janson Industries
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 preparation
Process 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 preparation
Process 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
Notice that when module is
finished the statement after the
Call is executed
Copyright 2014 by Janson Industries
“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
Module 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
Flowgorithm Flowcharts
Doesn't have modules, has
functions
Creating the main method is
standard
Create new flow chart (File, New)
Flowgorithm puts “”Main” text in Start
oval and "End" text in the Finish oval
Copyright 2014 by Janson Industries
Add I/O symbols and text to
display then double click on arrow
30
between I/O symbols…
… then click Call symbol
31
Copyright 2014 by Janson Industries
Flowgorithm Method Call
In flowchart, double click Call symbol
and enter name of method followed
by ()
32
Copyright 2014 by Janson Industries
Flowgorithm Function Definition
Click Add Function button
Specify
Function
name
33
Copyright 2014 by Janson Industries
Flowgorithm Method Definition
showCustAddress FC
created and displayed
Simply add symbols to
showCustAddress
To display Functions
click drop down arrow
and select
34
Copyright 2014 by Janson Industries
Flowgorithm Method Definition
Run
35
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
36
Copyright 2014 by Janson Industries
Java Method Call
To invoke the method from within
the java class
Method name
Parenthesis
Semicolon
showCustAddress();
37
Copyright 2014 by Janson Industries
Java Method Call
Here's the Java solution of the method call
38
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
39
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
40
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
41
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()
Its scope is limited to the main
method
Copyright 2014 by Janson Industries
42
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
43
Copyright 2014 by Janson Industries
Method Call Values
When method called, data is 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
44
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
45
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
46
Flowgorithm Call Values
When inserting the call
symbol, can specify
arguments/values to be
passed
Syntax same a pseudocode
47
Copyright 2014 by Janson Industries
Flowgorithm Call Values
When creating the function,
click Add to specify variables
to hold the passed values
48
Copyright 2014 by Janson Industries
Flowgorithm Function Parameters
Specify variable name and
data type
Have to click Add again to
define second variable
49
Copyright 2014 by Janson Industries
Flowgorithm
Of course, must insert
statement(s) to the
new Function (add)
50
Copyright 2014 by Janson Industries
Flowgorithm Function Parameters
Voila!
You have created a
Function that
accepts values
51
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);
}
52
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);
}
53
Copyright 2014 by Janson Industries
Java
54
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 variables
Global variables
55
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
56
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
57
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
58
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
59
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
60
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
Flowgorithm does not support
global or reference variables
61
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
Must be defined as static
62
Copyright 2014 by Janson Industries
Java
63
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()
64
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
65
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!
66
Copyright 2014 by Janson Industries
Method Call Non-Graded Assg1
Send StringModuleCall.txt to me
([email protected]) as an email
attachment with the topic
C3NGA1
67
Copyright 2014 by Janson Industries
Method Call Non-Graded Assg2
Based on the pseudo code in
StringModuleCall.txt create an
Flowgorithm flowchart
Store the flowchart in a file
called StringModuleCall.fprg
Email the flowchart as an
attachment with the topic of
C3NGA2
68
Copyright 2014 by Janson Industries
Method Call Non-Graded Assg3
Create a java program to perform
the same function, however, use
one global variable called
stuName
Instead of name and userName
Store the java code in a file called
StringModuleCall.java
Email the java file as an
attachment with the topic of
Copyright 2014 by Janson Industries
C3NGA3
69
Lab Assgs
Non-graded
Chap 3 Labs 2.1 through 2.4
Graded
Chap 3 Lab 2.5
Send work as email
attachments with topic C3Lab
70
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
71
Copyright 2014 by Janson Industries