Скачать презентацию Intro to Programming Algorithm Design Modules Assg

fdd33e5374b589a4a59237b615e337fc.ppt

• Количество слайдов: 71

Intro to Programming & Algorithm Design Modules Assg 1 Assg 2 Assg 3 Labs This presentation can be viewed on line at: ch 03. Introto. Prog. 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 Oil. Calc java example, you created one method called main 3

// // Oil. Calc. 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 Oil. Calc { 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. next. Int(); // 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 Oil. Calc) 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 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 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 n n n 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 show. Cust. Address() Display “Joe Customer” Display “ 1 Main St. ” Display “Enid, OK 56565” End Module 10

Pseudo Code Modules n Any module can invoke another module with the call command Module main() Call show. Cust. Address() End Module n The pseudocode for the entire program would be Module main() Call show. Cust. Address() End Module Copyright 2014 by Janson Industries Module show. Cust. Address() Display “Joe Customer” Display “ 1 Main St. ” Display “Enid, OK 56565” End Module 11

Good Module Names n Module name standards: u u u n Good examples u u n Copyright 2014 by Janson Industries One "word" (no spaces) Begins with lower case letter Use camel casing Describes processing Followed by parenthesis () calc. Sales. Total() get. Cust. Address() Bad examples u c. ST(), calcst, get. CA 12

Top Down Design n How do you decide what a module consists of? u u Examine each subtask and break it down into further subtasks u n Break the program into 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 n What are things/tasks you have to do to make a cake u Ingredient preparation u Process the ingredients u Assemble the cake 14 Copyright 2014 by Janson Industries

Bottom Up Design n n Look at all the individual steps and group them into logical units Also called Abstraction 15 Copyright 2014 by Janson Industries

Modularization n n Abstraction creates larger tasks out of a series of individual steps For instance, Aristotle looked at the world around him and created abstract groups u u Copyright 2014 by Janson Industries Collies, dachshunds, poodles made up the group dogs Calicos, tabbies, Siamese were cats Cats, dogs, horses, etc. were mammals Mammals, birds, reptiles were animals 16

Modularization n Aristotle created these abstract groups u u Phylums u Species u Copyright 2014 by Janson Industries Kingdoms Etc. 17

Abstraction Example n Many steps to make a cake u u u u Copyright 2014 by Janson Industries 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. 18

Abstraction n We could create modules u u u u 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 n We could then group these modules into larger groups like u Ingredient preparation u Process the ingredients u Assemble the cake 20 Copyright 2014 by Janson Industries

Abstraction n n How do you show the relationship between all the modules? Hierarchy chart u Shows many levels of abstraction u Shows relationship between modules u 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 n n n 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: u u u Invert cake Remove cake from pan Place on cellophane 23 Copyright 2014 by Janson Industries

Hierarchy Chart n For a sales transaction, same thing u u u u Read and store 1 st item and qty Read and store 2 nd 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 n Each module/method has a separate FC u FC starts with module/method name and “()” in oval shape u All (except main) end with text “Return” in oval F Copyright 2014 by Janson Industries That’s because program control returns back to the next statement after the call when the called module completes “ 26

Modules n 1 For instance the following statements are executed in this Module main() order 2 6 Display “Howdy” Call show. Cust. Address() Display “See ya” End Module 3 4 5 Module show. Cust. Address() Display “Joe Customer” Display “ 1 Main St. ” Display “Enid, OK 56565” End Module n Copyright 2014 by Janson Industries Notice that when module is finished the statement after the Call is executed “ 27

Flowcharts n And the following would be displayed Howdy Joe Customer 1 Main St. Enid, OK 56565 See ya n Module call shown in new symbol with module/method name in middle of box followed by parenthesis module. Name() Copyright 2014 by Janson Industries “ 28

Module Call main() Display “Howdy” show. Cust. Address() Display “Joe Customer” Display “ 1 Main Street Display “See ya” End Display “Enid OK, 56565” Return Copyright 2014 by Janson Industries 29

Flowgorithm Flowcharts n n Doesn't have modules, has functions Creating the main method is standard u Create new flow chart (File, New) F n Copyright 2014 by Janson Industries Flowgorithm puts “”Main” text in Start oval and "End" text in the Finish oval Add I/O symbols and text to display then double click on arrow 30 between I/O symbols…

n … then click Call symbol 31 Copyright 2014 by Janson Industries

Flowgorithm Method Call In flowchart, double click Call symbol n and enter name of method followed by () 32 Copyright 2014 by Janson Industries

Flowgorithm Function Definition Function button Click Add n n Specify Function name 33 Copyright 2014 by Janson Industries

Flowgorithm Method Definition n show. Cust. Address FC created and displayed Simply add symbols to show. Cust. Address To display Functions click drop down arrow and select 34 Copyright 2014 by Janson Industries

Flowgorithm Method Definition n Run 35 Copyright 2014 by Janson Industries

Java Method Create a method outside of the main method with header that has n u Access info, return value type, method name and () public static void show. Cust. Address() { } F n The keyword void means no value is returned Enter method statements inside braces 36 Copyright 2014 by Janson Industries

Java Method Call n To invoke the method from within the java class u Method name u Parenthesis u Semicolon show. Cust. Address(); 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 n When a variable is defined in a method, it can only be accessed by statements within that method u n 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 n This is OK Module main() Declare String name = “Joe” Display name Call show. Name() End Module show. Name() Declare String name = “Sam” Display name End Module n A program can have two local variables with the same name u Because their scopes are separate 40 Copyright 2014 by Janson Industries

Local Variables n This is not OK Module main() Declare String name = “Joe” Display name Declare String name = “Sam” Display name End Module n These two local variables called name have the same scope u Because their scopes are not separate this will cause an error when compiled 41 Copyright 2014 by Janson Industries

Local Variables n This is not OK Module main() Declare String name = “Joe” Call show. Name() End Module show. Name() Display name End Module n Because name is defined in main() it cannot be accessed in show. Name() u Copyright 2014 by Janson Industries Its scope is limited to the main method 42

Local Variables n n 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 n n 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 = a + b Display result End Module 44 Copyright 2014 by Janson Industries

Method Call Values n Final program Module main Call add(2, 3) End Module add(Integer a, Integer b) Declare Integer result = a + b Display result End Module 45 Copyright 2014 by Janson Industries

Method Call Values n Can pass variables instead of static values Module main Declare Integer first. Num, second. Num Display “Input first number to add” Input first. Num Display “Input second number to add” Input second. Num Call add(first. Num, second. Num) End Module add(Integer a, Integer b) Declare Integer result = a + b Display result End Module Copyright 2014 by Janson Industries 46

Flowgorithm Call Values n When inserting the call symbol, can specify arguments/values to be passed u Syntax same a pseudocode 47 Copyright 2014 by Janson Industries

Flowgorithm Call Values n When creating the function, click Add to specify variables to hold the passed values 48 Copyright 2014 by Janson Industries

Flowgorithm Function Parameters n n Specify variable name and data type Have to click Add again to define second variable 49 Copyright 2014 by Janson Industries

Flowgorithm n Of course, must insert statement(s) to the new Function (add) 50 Copyright 2014 by Janson Industries

Flowgorithm Function Parameters n Voila! u You have created a Function that accepts values 51 Copyright 2014 by Janson Industries

Java n Very similar to pseudo code // Method. Call 1. java // R. Janson 1/3/2015 // This pgm calls a method and passes two integers import java. io. *; import java. util. Scanner; public class Method. Call 1{ // 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 n Very similar to pseudo code // This method prompts, gets, and passes two integers to the // add method } public static void main(String[] args){ int first. Num, second. Num; Scanner keyboard = new Scanner(System. in); System. out. print("Input first number to add "); first. Num = keyboard. next. Int(); System. out. print("Input second number to add "); second. Num = keyboard. next. Int(); add(first. Num, second. Num); } 53 Copyright 2014 by Janson Industries

Java 54 Copyright 2014 by Janson Industries

Method Call Values n Problem: multiple local variables with the same values u first. Num and a u second. Num and b n Takes up extra memory space n A couple ways around this u Reference variables u Global variables 55 Copyright 2014 by Janson Industries

Method Call Values n Currently when values assigned and passed Main Memory Module main Declare Integer first. Num = 2 Declare Integer second. Num = 3 Call add(first. Num, second. Num) End Module 2 3 Module add(Integer a, Integer b) Declare Integer result = a + b Display result End Module first. Num 2 second. Num 3 a 2 b 3 56 Copyright 2014 by Janson Industries

Reference Variables n Don’t hold a value, simply reference (point to) another value Main Memory Module main Declare Integer first. Num = 2 Declare Integer second. Num = 3 Call add(first. Num, second. Num) End Module add(Integer Ref a, Integer Ref b) Declare Integer result = a + b Display result End Module first. Num 2 second. Num 3 a b 57 Copyright 2014 by Janson Industries

Reference Variables n Changes to the reference variables change the original variable’s values Main Memory Module main Declare Integer first. Num = 2 Declare Integer second. Num = 3 Call add(first. Num, second. Num) End Module add(Integer Ref a, Integer Ref b) a=8 b=6 End Module first. Num 8 second. Num 6 a b 58 Copyright 2014 by Janson Industries

Global Variables n Accessible to all modules within the program u n 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 n Advantages: less code, fewer variables, no need to pass vars Declare Integer first. Num, second. Num Module main Display “Input first number to add” Input first. Num Display “Input second number to add” Input second. Num Call add() End Module add() Declare Integer result = first. Num + second. Num Display result End Module Copyright 2014 by Janson Industries 60

Global Variables Disadvantages: n u Since any method can access, harder to find errors with that global variable's value u Makes the module less independent/self-contained F n I. e. it needs the global variable to work Flowgorithm does not support global or reference variables 61 Copyright 2014 by Janson Industries

Java n n n 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 u Must be defined as static 62 Copyright 2014 by Janson Industries

Java 63 Copyright 2014 by Janson Industries

Method Call Non-Graded Assg 1 n n n Create pseudocode for a program called string. Module. Call Save the pseudo code in a text file named String. Module. Call. txt Define string. Module. Call to have two modules called u main() u print. Name() 64 Copyright 2014 by Janson Industries

Method Call Non-Graded Assg 1 n Define main to u Create a local String variable called name u Prompt the user for their first name F “Please enter your first name” u Assign the inputted text to the variable name u Call print. Name and pass the local variable name to print. Name 65 Copyright 2014 by Janson Industries

Method Call Non-Graded Assg 1 n Define print. Name to u Accept a string value and assign it to a local variable called user. Name u Display user. Name with the following text F u "Hi user. Name, nice to meet you!" So, if the user had entered Joe, the result would be F Hi Joe, nice to meet you! 66 Copyright 2014 by Janson Industries

Method Call Non-Graded Assg 1 n Send String. Module. Call. txt to me (rjanson@fscj. edu) as an email attachment with the topic C 3 NGA 1 67 Copyright 2014 by Janson Industries

Method Call Non-Graded Assg 2 n n n Based on the pseudo code in String. Module. Call. txt create an Flowgorithm flowchart Store the flowchart in a file called String. Module. Call. fprg Email the flowchart as an attachment with the topic of C 3 NGA 2 68 Copyright 2014 by Janson Industries

Method Call Non-Graded Assg 3 n Create a java program to perform the same function, however, use one global variable called stu. Name n n n Copyright 2014 by Janson Industries Instead of name and user. Name Store the java code in a file called String. Module. Call. java Email the java file as an attachment with the topic of C 3 NGA 3 69

Lab Assgs n Non-graded n n Graded n n Chap 3 Labs 2. 1 through 2. 4 Chap 3 Lab 2. 5 Send work as email attachments with topic C 3 Lab 70 Copyright 2014 by Janson Industries

Points to Remember n Breaking programs into modules is good design because it results in code reuse u Decreases program size u Decreases program complexity u Decreases cost of program development u Decreases cost of modifying a program 71 Copyright 2014 by Janson Industries