# Subroutines

:

We are basically done going over the three controls “structures” of programming: sequential, conditional and loop. This means that we have all the tools we need to write any program. There are however, other features to make programming better (more efficient). These two features (for us) are subroutines and arrays. Subroutines (and probably arrays) are the difference between a good program and a bad program. Subroutines consist of breaking up a problem into smaller parts and then somehow putting them together again.

Subroutines (the 2 hardest topic of the semester)

nd

Subroutine Syntax

To present this topic, we will use an example of a program (just 3 lines) that we would not normally use a subroutine with, but, for simplicity sake, and ease of explanation, we will write it using a subroutine.

Our simple three-line program:

INPUT a, b, c sum = a + b + c DISPLAY sum

The best way to represent this program, using subroutines, is to use a “structure chart”.

MAIN

INPUTS

CALC

PRINT

Using subroutines this program is really broken down into four separate programs with “main” as the boss program.

Here is what our program would look like broken down into the separate problems:

(1) MAIN

A1 Call INPUTS A2 Call CALC A3 Call OUTPUT A4 END

(2) INPUTS

B1 INPUT a, b, c B2 RETURN

(3) CALC

C1 sum = a + b + c C2 RETURN

(4) OUTPUT D1 DISPLAY sum D2 RETURN Note: The use of “RETURN” at the end of each separate program – this returns it to the “MAIN”. a Statement Number A1 1 B1 B2 A2 C1 C2 A3 D1 D2 A4 b c sum Output 2 3 6 6 .

b. “OUTPUT” needs the value of “sum” from “MAIN”. “INPUTS” doesn’t need anything from “MAIN”. . but “INPUTS” need to give / send the values of a. b. Our “CALC” subroutine needs the values of a. In our “subroutine” for input. 1. and c to “MAIN”. and c from “MAIN” and needs to send the value of sum back to “MAIN”. 2. 3.Communication between modules There are a few points to discuss in regards to this aspect of our subroutined program.

So learn and understand the concept behind them! Global Variables There are 2 ways to share data in subroutines: 1. if any global variables in a program.Note: These concepts about “communication” are a very important concept to understand. There are good reasons for using very few. . Global Variables – you are telling the translator that every module can retrieve from or store to the variable using the name.

Local Variables – it is also possible to declare a variable as a local variable within a particular module. Lets change 2 lines of our present program: MAIN Call INPUTS Call CALC Call OUTPUT END INPUTS . as long as you are executing the statements within that particular module. The local variable does not exist as far as the other modules are concerned. These variables are treated in the same old way that you are used to.2.

It is a “local variable”. c RETURN CALC temp = a + b sum = temp + c RETURN OUTPUT DISPLAY sum RETURN Did you find the new line? This variable isn’t a global variable like the other variables. It hasn’t been declared. It shouldn’t and isn’t known by the other subroutines. b.INPUT a. It OUTPUT were to use temp as a variable. . it couldn’t be processed (syntax error).

That is because temp is a local variable. This is only where global variables are declared.Here is the same problem written in Visual Basic: Option explicit ‘declare global variables’ dim a as integer dim b as integer dim c as integer dim sum as integer ‘Notice temp has not been declared here. .

Private sub cmdMain_click() call INPUTS () call CALC () call OUTPUT () End Sub _______________________________________________________ Sub INPUTS () ‘To get this. if the variable isn’t found. “Temp” is a local variable that is there only to insure that information isn’t shared. Then. let alone available to “echo”. . The variable would be undeclared. If it is not found there. Notice that the “temp” variable isn’t available to the other subroutines. it will look for it in the “global” variable location.’ Print sum End Sub Note: Take careful note of our “CALC” subroutine. hit the <enter> key.’ a = inputbox (“………”) b = inputbox (“………”) c = inputbox (“………”) End Sub ‘In Visual this is our RETURN’ _______________________________________________________ Sub Calc () dim temp as integer temp = a + b sum = temp + c End Sub _______________________________________________________ Sub OUTPUT () ‘OUTPUT can echo the variables. The first place that a program will look for a variable is within it’s own subroutine. then that will come up as a syntax error. They are global.

This will only be a 4-inning baseball game. We will need to use two variables and a loop that goes 4 times.Ex. Subroutine using a loop: We need a program that will keep the score of a baseball game. Dodgers = 0 Giants = 0 totalinnings = 4 For innings = 1 to totalinnings INPUT score .

because the teams are playing 3 games this weekend!!! We will need a loop that goes 3 times. But alas.Dodgers = Dodgers + score INPUT score Giants = Giants + score ENDFOR DISPLAY Dodgers. we want a grand total for each team. we don’t need to worry about all those loops. This could present a change. Giants Now. we have to change this program slightly. but it would take place outside the loop. How would you alter the previous program to accomplish the change? You would probably need to create several different loops. To put the icing on the cake. We can use subroutines!!!!!!!! The previous program will be our subroutine “Play1Game”. MAIN NumGames = 3 DodgersGrandT = 0 GiantsGrandT = 0 FOR game = 1 to NumGames CALL Play1Game DodgersGrandT = Dodgers GrandT + Dodgers .

GiantsGrandT = GiantsGrandT + Giants ENDFOR DISPLAY DodgersGrandT. The only problem that exists is that “totalinnings = 4” in our “Play1Game” should be moved to our “MAIN” program so it wouldn’t have to be executed numerous times. This type of approach is needed with a large program. GiantsGrandT Play1Game Dodgers = 0 Giants = 0 totalinnings = 4 For innings = 1 to totalinnings INPUT score Dodgers = Dodgers + score INPUT score Giants = Giants + score ENDFOR DISPLAY Dodgers. . Giants This program works more efficiently. IT WILL HAUNT YOU LATER. Keep in mind what is actually happening between our two programs: “MAIN” needs the Dodgers and the Giants score from “Play1Game” and in turn. “Play1Game” needs “totalinnings” from the “MAIN” program. we want to keep all of our constants at the beginning of our “MAIN” program. Also. THIS IS VERY IMPORTANT.

we will start designing subroutines – in other words. Now. Remember.Design Up until now. top-level design. toplevel design (subroutines) includes breaking a bit problem into smaller problems. . From there. which is also called high-level or architectural design. we proceed to detailed design. we have been designing algorithms.

INDEPENDENT TASK OR PROBLEM .The Process of Design There are two approaches: 1. Object-oriented approach (which is used more often) Guidelines: The most important guideline that we should concentrate on is this: EACH SUB-PROGRAM SHOULD CORRESPOND TO SOME EASY-TOUNDERSTAND. Top-down functional design 2.

and making some sort of inquiry about books. For example: representing a customer might require data such as name. Modular decomposition. 2. . which contains both the data and the behaviors. the designer would design a “customer” object. The designer must consider the data to represent the state of each object and the behavior that each object might be expected to exhibit. address and phone number. Task oriented approach – Step-wise refinement. and behaviors like buying a book.1. Object-oriented approach – looks at the problem and decomposes it into the various “objects” that comprise the problem. In the object-oriented approach. ordering a book.

We will start with a small problem to demonstrate the process***** Our goal: Print the following information pertaining to bowling scores. Bowlers Averages 200 190 210 200 .

Team Average” (the second vice-president) “Calc. This is to keep it simple!! We could also have “Bowling” display individual averages and the . “Calc. Second. we need to calculate a team average. lets calculate the average of each bowler. ********THE KEY: WHAT INFORMATION DOES EACH “LEVEL” NEED?******** We have 3 different “levels” at the moment: 1. “Bowling” (the president) 2.Team Average (4 bowlers each) 200 First off. Team Average” should get the total of all averages. “Calc. Average 1 bowler” (the vice-president) 3.

team averages. because it is only one line.” Should “numgames” be a global or a local variable? The professor chooses global. REMEMBER: “Design is a matter of decision. Team Average”. Who should set the number of bowlers? Who should calculate the total of all the averages? NOTE: We could let the president take care of the “Calc. but we will do it this way for now. The President’s Job (“Bowling”) MAIN numgames = 3 numbowlers = 4 CALL CalcAverage1Bowler What’s wrong with this? We need a loop or we will create more work for the . but we will let the middle management handle it.

add scores 2. get scores. so far for this segment: . MAIN numgames = 3 numbowlers = 4 FOR bowlers = 1 to numbowlers CALL CalcAverage1Bowler sum = sum + avg ENDFOR CALL CalcTeamAverage END CalcAverage1Bowler (segment): Tasks: 1.computer and ourselves. divide Here is our structure chart.

CalcAverage1Bowler totscore = 0 FOR scores = 1 to numgames CALL Get1ValidScore totscore = totscore + score ENDFOR avg = totscore / numgames RETURN Calc. we will make them “local” for convenience sake.Note: Usually. Average Get Scores & Add Scores Divide GetValidScore segment: . but in this case. we make constants “global”.

The three secrets of Designing “good” modules: . in MAIN all variables are “global”.GetValidScore INPUT score WHILE score < 0 or score >300 INPUT score ENDWHILE RETURN Note: There are local constants here!!! Are there any values in MAIN that are not shared? No.

make them black boxes. Then determine the sub-tasks that need to be done for each of the tasks. Secret 2: When designing and implementing modules. Secret 3: When using modules practice abstraction.Secret 1: Always decompose problems based on tasks. Make sure your module has no unintended side effects. Make those modules. In the preconditions and post conditions make sure each module provides all of the information needed to use the module. THINGS TO REMEMBER: . Keep going until the tasks are small enough to attack at the pseudocode level.

Arrays . 3.1. 2. More than one module can make calls to the same module. The common use of modules is in programs with menus. Modules can call other modules. The MAIN modules are not the only modules that can make subroutine calls.

and 1 and 4. 5 and 4. Then.b. we can do this using a loop: max = 300 . this is fine. I want to print the difference between each number and the average. I want to find the difference between 6 and 4. and 1. Ex: For the variables of 6.Here is the problem: I want to write an algorithm that adds up 3 different numbers and prints the average. 5.c Sum = a + b + c Avg = Sum / 3 DISPLAY a – Avg DISPLAY b – Avg DISPLAY c – Avg END Okay. For the algorithm we have: INPUT a. but what if we want to do the same with 300 numbers? Well.

We can use and array. Ex: This is what our “memory location” looks like: .FOR x = 1 to max INPUT num sum = sum + num ENDFOR Avg = sum / max END Okay. we’re done right? WRONG!!! What about finding the difference between each number and the average? We can have the user re-enter the 300 numbers!!!!! There are two ways to solve this problem: 1. We can have the program read the information from a file. 2.

Numbers (1) (2) (3) (4) (5) 5 3 9 2 8 Referring to values in the array: Numbers(1)= 5 Numbers(1+4)=8 In Visual Basic the declarations will be: // declare an array called Numbers that holds 5 integers Const Max=5. Dim Numbers (Max) as Integer .

Continuing on from our initial “dim” statement. Note: The dim (declaration statement) means that Numbers(Max) has 5 locations. we need to be able to use each individual slot! What can we do? We use a subscript – and the way we accomplish this in a program is: Numbers(1). and etc. but outside of the declarations statement. it means (Numbers(5)) memory location 5 that is within “Numbers”. Numbers(2). here are some examples of “the way an array works”! Fun with Arrays max = 5 dim Numbers(max) as integer Numbers(3) = 21 (location 3 gets the value of 21) Numbers(2) = 16 (location 2 gets the value of 16) Numbers(5) = Numbers(3) + Numbers(2) (memory location 5 gets 37) Numbers(1) = Numbers(3 – 1) (location 1 gets 16) .But.

They are separate variables. max = 3 sum = 0 FOR x 1 to max INPUT num(x) sum = sum + num(x) ENDFOR avg = sum / max FOR y 1 to max DISPLAY num(y) – avg ENDFOR END Where do all the numbers get input? In num(x) .Numbers(4) = Numbers(3) – 1 (location 4 gets 20) Print Numbers(4 + 1) + 1 (this displays 38) x= 3 y = 2 (These last two statements have nothing to do with an array. Numbers(14) doesn’t exist.) ******************************************************************************* Now. back to our first problem. Remember that we wanted to add up our numbers. and then print the difference between each variable and the average. There is no Numbers(0)) Print Numbers( x + y + 10) (This would also result in an error. print the average. Print Numbers(x – y) (This would result in an error.) Print Numbers(x) (this displays21) Numbers(y) = Numbers(x) (Numbers(2) gets replaced with 21) x= x – 1 Print Numbers(x) (this displays 21) Here are some more examples (potential test questions) using the above “memory location” values.) Numbers(x) = 5 (Numbers(2) gets 5) Print Numbers(Numbers(y)) (Displays 37. This is the prof’s Favorite question.

with Sequential Search Ex: The Problem: We want to input a student’s name and print out their final exam grade.Note: is this confusing? • Be able to declare arrays and perform desk checking algorithms containing arrays • Be familiar with concept of Parallel Arrays. so the Names array’s first element is referring to the Grades array’s first element Subscript (1) Joe Names Subscript Grade . one to hold the names. We declare two arrays. Finding the student’s grade when we enter the name. We keep these two in parallel. other one to hold grades.

(2) (3) (4) (5) Mary Hal Phil Anne (1) (2) (3) (4) (5) 80 90 77 93 81 The idea is when the user enters the name “Hal”. Therefore we need to determine which subscript corresponds to a particular name. Here is our structure chart for this problem: . it should display 77.

Target // contains the string to search for each name is // Names array is unique. . What does “Main” need? Main FindAScore GetData Search for Student Grade: // Preconditions: Max has the number of elements in Names and // Grades array. What does “FindAScore”need? 3. Each grade corresponds to the // name with a matching subscript.1. What information does “GetData” need? 2.

//postconditions: The Grades element corresponding to the target is displayed location contains the subscript where target was found. Program pseudocode: MAIN sentinel = -99 max = 5 CALL GetData INPUT Target //priming read WHILE Target <> sentinel CALL FindAScore INPUT Target ENDWHILE END GetData (This is the easy one!!!) FOR I 1 to Max INPUT Names(I) INPUT Score(I) ENDFOR Return FindAScore This is the had one!!!!! FOR I = 1 to max IF Names(I) = Target DISPLAY Score(I) ENDIF ENDFOR .

// Preconditions: Max has the number of elements in Names // and Grades array each grade corresponds to // the name with a matching subscript Target // contains the string to search for each name is // Names array is unique //postconditions: If there is a name in Names that matches target. but there is a problem.Return Note : All right this works. We also need something that will tell us that the Target isn’t in our index. We need a smarter loop to be more efficient. // then the Grades element corresponding to the . This program will go through all the loops even if the score is found at the beginning.

// // // FindAScore target is displayed and Found is “T”. the message “not found” is displayed and Found is “F” found ”F” Index1 WHILE Index <= max AND found=”F” IF Names(Index) = Target THEN LocationIndex Found”T” ENDIF IndexIndex+1 ENDWHILE IF Found = “ T” THEN DISPLAY Grades(Location) ELSE DISPLAY “Not Found” ENDIF Return Do Not Do This Found = “F” FOR Index = 1 to max IF Names(Index) = Target THEN DISPLAY Score(Index) Found = “T” . if there is // no match.

Index = max + 1 ENDIF ENDFOR IF Found = “F” THEN DISPLAY “Not Found” ENDIF Return • Be familiar with concept of Sorting an array • Know what is meant by Bubble Sort and its improvements Values 22 93 44 5 22 44 93 5 22 44 5 93 1) it took one less than number of elements in array 2) the smallest value has not made it to the top. .

22 5 44 93 5 22 44 93 This algorithm will need two loops.(compare element(n-1) to element(n)) . an inner loop to compare each element. and that loop will have n-1 iterations We also need an outer loop to force the inner loop go n-1 times FOR i 1 to n-1 // outer loop For j 1 to n-1 // inner loop Compare elements and swap if needed ENDFOR ENDFOR FOR i 1 to n-1 // outer loop FOR j 1 to n-1 // inner loop IF Values(j)> Values(j+1) THEN TempValues(j) Values(j) Values(j+1) Values(j+1)Temp ENDIF ENDFOR ENDFOR Two problems: compares all the way to the end every time Does not care if the array is already sorted First Improvement: -Two Way Bubble Sort The first time through the loop we want to compare all the way to the last element.3) In this worst-case the smallest number has only moved one step up.

For i 1 to n-1 For j 1 to n-i IF Values(j)> Values(j+1) THEN TempValues(j) Values(j) Values(j+1) Values(j+1)Temp ENDIF ENDFOR ENDFOR Second improvement: Bubble Sort with Flag Even with Two. Therefore. we only go as far as comparing element(n-2) with element(n-1) and on the next one compare element(n-3) with element (n-2). Sorted”F” WHILE Sorted =”F” Sorted.“T” // set for inner loop FOR i 1 to n-1 FOR j 1 to n-i IF Values(j)> Values(j+1) THEN Sorted”F” TempValues(j) Values(j) Values(j+1) Values(j+1)Temp ENDIF ENDFOR ENDFOR ENDWHILE Here is a scenario: We have five teams and want to enter each team and the number of games that they have won into two different arrays. we still have the problem of not caring whether the array id already sorted. Here is the algorithm: max = 5 FOR x = 1 to max INPUT teams(x) INPUT games(x) . So we need a flag to tell us if any swaps were there.Way bubble sort.The second time.

they are parallel arrays. That is because one is a string and one is a number. Therefore.ENDFOR END Teams and games use the same subscript. Explanation of the two “loops” within this program: For I = 1 to max – 1 FOR j = 1 to max – 1 -----------------------------------------------------------------------etc------ . Now we need to sort from highest to lowest number of games won: FOR I – 1 to max – 1 FOR j = 1 to max – 1 IF games (j) < games(j + 1) THEN temp = games (j) games(j) = games (j + 1) games(j + 1) = temp temp2 = teams(j) teams(j) = teams(j + 1) teams(j + 1) = temp2 ENDIF ENDFOR ENDFOR Note: Notice that we can’t use the same variable name (temp) for games as we use for teams.

(1) (2) (3) (4) (5) 162 189 159 200 197 How would we change our program to DISPLAY the worst team to the best? (Considering that the array is already sorted from highest to . we compare the value of one “slot” with the next value in the array. because (max = 5) to completely sort the array. The next value would be garbage! Thus. The “max – 1” in the j loop is because. considering the way the bubble sort works. we need to “loop” through it 4 times (not 5).******The “max – 1” in the I loop is there. we don’t want to compare it to the next value. This means that when we reach slot #5. we need a “max – 1” in there.

lowest)

Like this: h = max WHILE h >= 0 DISPLAY h=h–1 ENDWHILE Note: This is only a part of the program, but it is the only part that we would need to change. Okay, How would you change it to DISPLAY the games won of a particular “INPUT” team: INPUT target FOR I = 1 to max IF teams(i) = target THEN DISPLAY games(i) ENDIF ENDFOR Using a WHILE loop: INPUT target I=1 WHILE I <= max IF teams(I) = target DISPLAY games(I) ENDIF ENDWHILE

One last thing:

What if we knew that our array was in ascending order? There exists a better search for this situation:

Binary Search If the array is in order(ascending or descending) there is a fast search algorithm called binary search. 1 2 3 4 5 6 7 8 9 10 5 12 19 54 98 112 144 200 242 350

We are looking for the target, which is 54 1. need to find the middle element (first subscript + last subscript)/2 (1+10)/2 = 5.5 take the integer part 2. so numbers(5)= 98 does not equal the target 3. now we look to see if the middle element is greater than 98, there is no reason to look for the target anywhere further down the array 4. we need to look for the top half (1+4)/ 2 5/2= 2.5 take the integer part 2 5. is numbers(2) = to target? No 6. look to see if the numbers(2) is greater than target? No 7. so we eliminate the top half of remaining array, so the new array is from subscript 3 till subscript 4 8. (3+4)/2= 3.5 take integer part is 3 9. compare the numbers(3) with target, they are not equal. 10. is numbers(3) greater than target? No, so the first subscript is 4 and last one is also 4. (4+4)/ 2= 4 11. is numbers(4) equal to target? Yes, we are done with the search.

Desk checking algorithms that contain arrays:

1 max 3 2 FOR Ind 1 to max 3 nums(Ind) Ind * 10 4 ENDFOR 5 Ind max 6 WHILE Ind > 0 7 DISPLAY numbs(Ind) 8 Ind Ind – 1 9 ENDWHILE 10 END

10 Statement Number Output .20.Expected Input List: None Available Output List: 30.

Learning to Share Top-Level Design involves two related tasks: 1. . Determining how the various pieces should communicate with each other. 2. The act of decomposing a problem into pieces. The subject of this chapter is the second task.

which another module was using. Use of parameters. 2. A local variable is one.In the earlier chapter. . Use of global variables. A global variable is one. which is only used within a module and is not available to any other module. The danger of this is that one module may change the value of a variable. Two ways that modules can share data: 1. modules communicated using global variables and this method worked just fine. Every variable had a name and every module had access to each variable. which is available to all modules. 2. Such an error is devastating to the logic of the program and is also very hard to locate. Local and global variables: 1.

and especially parameters. That is only needed by one module. . contribute to the idea of writing and using black box modules (with information hiding). There are many variables in a large program. By making such variable local.Try to consider throughout this chapter how local variables. you take away the possibility that some other module(being written by another team) might change the value stored there.

What is a side-affect? A side-affect is something within the entire program that gets affected within a subroutine. Because of these “side-affect”. This usually occurs when using “global variables”. . parameters are used in place of most “global variables”.

Parameters The one rule for parameters: you can use parameters to share data only between a calling module and a called module. .

most difficult topic for the semester) Here is a sample. sum. avetemp . non-sense.Parameters (last. terrible program (to prove a point): MAIN INPUT n Call Addemup Call Temperatures Print n.

This program is a mess. and so does n.END Addemup sum = 0 FOR i 1 to n sum = sum + n ENDFOR Return AveTemp sum = 0 INPUT n FOR i 1 to n INPUT temp sum = sum + temp ENDFOR avetemp = sum / n Return Why doesn’t this program work worth a darn? 1. Which variables are global? a. avetemp and n a global variables. sum. When we need to share what do we do? . b. But sum gets changed in 2 or the subroutines. It’s to easy for somebody to step on someone else’s “global” variables! Don’t get me wrong – global constants are a good thing.

Structure chart for our NON-Sense Program using parameters: .

n sum sum AveTemp Note the arrows. parameters! These arrows are actually .

that’s correct. to you” Return Yes. Dear “___________ DISPLAY “Happy Birthday.Main AveTemp Addemup This is the famous “Happy Birthday Program” Happy FOR i 1 to 2 DISPLAY “Happy Birthday to you “ ENDFOR DISPLAY “Happy Birthday. we want the name of someone to go in the space! How do we get a name in there??? .

Dear “___________ DISPLAY “Happy Birthday.First Way: //Global Person Person = “Fred” CALL Happy Person = “Mary CALL Happy Happy FOR i 1 to 2 DISPLAY “Happy Birthday to you “ ENDFOR DISPLAY “Happy Birthday. to you” Return .

Dear “___________ DISPLAY “Happy Birthday. to you” Return .Second Way – Parameters (The better way) Main //local variable person Person = “Fred” CALL Happy(Person) //This sends the value of “person” to Happy Person = “Mary” Call Happy(Person) END Happy(value parameter person) FOR i 1 to 2 DISPLAY “Happy Birthday to you “ ENDFOR DISPLAY “Happy Birthday.

Dear “___________ DISPLAY “Happy Birthday.Main //local variable person Person = “Fred” CALL Happy(Person) //This sends the value of “person” to Happy DISPLAY Person //Displays “Fred” Person = “Mary” Call Happy(Person) END Happy(value parameter person) FOR i 1 to 2 DISPLAY “Happy Birthday to you “ ENDFOR DISPLAY “Happy Birthday. to you” Person = “huh” DISPLAY Person //Displays “huh” Return .

The actual value inside the quotes gets sent to Happy. Main //local variable person Person = “Fred” CALL Happy(Person) //This sends the value of “person” to Happy DISPLAY Person //Displays “Fred” CALL Happy(“Mary”) INPUT Other CALL Happy(Other) END Note: Check out the statement “CALL Happy(“Mary”). because we haven’t given a value to that particular place in memory!! Get it???? . the value of “Person” only gets changed within “Happy”. and it does not get changed in “Main”. What would happen? We would send merely garbage.Understand this: Within our subroutine “Happy”. If we took out the quotes.

b //local variables CALL Diff(a.New Scenario: INPUTs: 7. value b)//2 parameters a = a – b DISPLAY a Return .2 Main INPUT a.b) DISLAY a //Displays 7 END Diff (value a.

b //local variables CALL Diff(6. value b)//2 parameters a = a – b DISPLAY a //Displays -3 Return .2 Main INPUT a.9) DISLAY a //Displays 7 END Diff (value a.Similarly: INPUTs: 7.

value b)//2 parameters a = a – b DISPLAY a //Displays -5 Return Have you figured out why???? Yep! What maters is the order that the values are sent.a) DISLAY a //Displays 7 END Diff (value a.INPUTs: 7.2 Main INPUT a. . b //local variables CALL Diff(b.

2 Main INPUT a. reference sum) sum = a – b DISPLAY sum Return Note: Pay attention to where we defined our parameters: Sub Diff(value a. It sends the value of sum back up to Main. .b. value b. b //local variables CALL Diff(a.sum) DISLAY sum //Displays 5 END Diff (value a. value b. reference sum). This new addition the “reference” addition is equivalent to an up arrow.INPUTs: 7.

c INPUT a.INPUTs: 6.2 Main // local variables a. reference sum) sum = a – b Return When you use parameters.b. b //local variables CALL Diff(a. the association of a parameter in the calling module is call the actual argument. value b.c) DISLAY c //Displays 4 END Diff (value a.b. The parameter in the called module is called the formal parameter or sometimes the dummy parameter .

inputs and outputs do not show up on a structure chart. As a result the invocation lines don’t need arrows. e) Every piece of information gets its own data couple. f) Global variable. . Data couples use little arrowheads to show which direction the data is going. that is. d) Data couples represent information that must be shared between modules. they indicate that one box calls the other. b) The straight lines joining two boxes on the chart are “invocation” lines. local variables. c) Calling modules are always higher up on the page than the modules they call.Points to Ponder: Structure Charts a) Structure charts show the modules of a system. and they show the parameter-based communication between those modules.

Num1 Num2 Sum Num1 Num2 The direction of the arrow shows which way the data is going. Some go both ways.Data Couples. A data couple is represented by an arrow on a structure chart (it has a circle at one end and an arrow head at the other). Some parameters communicate data down. . that is from the called module to the calling module. from the calling module to the called module.A data couple represents a single data item that is being shared or a data couple represents a parameter. Some parameters communicate data up.

That information is being communicated up to the calling module. .and-up Data Couples: The up-arrow couples carry information that was created in the called module. That information must be in the possession of the calling module. Calculate Sum Get Input Main The down-arrow couples carry information that is needed in the called module. but was created somewhere else.****ARROW UP: Reference parameter**** ****ARROW DOWN: Value parameter**** Down.

However. Any data couple on the structure chart. The couples provide important information to designers. Any data couple on the structure chart which points up. .1. maintenance programmers and others. the actual coding treats both of those couples the same. 2. which points down only is implemented as a value-type parameter. 3. and that includes the ones that point down and up is implemented as a reference-type parameter in most programming languages. testers. The difference between up and down and up data couples is purely logical for most programming endeavors.

between whom and in what direction. we decompose the problem into smaller problems. That is you can figure out what information needs to be shared. you can establish the necessary data couples. Even before considering any further subdivision of any of the modules.Top-Level Design Using Parameters: 1. 2. . First.

2. after a space. In the calling module. you include just the name of the parameter you are passing. the name of the module is followed by opening parentheses.The pseudocode syntax for parameter passing: 1. Then the parentheses are closed. when the module is called. we have the name of the parameter. . In the declaration for the called module. Then. Then the keyword reference is included. in parentheses.

.Functions: A function is a special case of the general concept of a module. A function gets “called” by using the function directly in an expression. A function is a module. which returns a value. A subroutine (procedure) gets called by the calling module as a single instruction.

Back to absolute value: Main Module INPUT Number CALL Calculate_Absolute_Value(Number.Answer) DISPLAY Answer END Calculate_Absolute_Value (value N. reference A) //Preconditions: N contains a value //Postconditions: A returns the absolute value of N IF N < 0 THEN A N*(-1) ELSE A N ENDIF .

and it seems like something someone else might have wanted to do one.RETURN As a function: Main Module INPUT Number Answer abs(Number) DISPLAY Answer END The function named abs() takes whatever value is passed to it and calculates the absolute value. look at the functions available in your language to see if maybe someone already wrote it for you. Ex. Most programming languages provide a wealth of builtin functions. Round a number Calculate sine Calculate cosine Calculate tangent Square Root Lesson: If you’ve got something you want to do. .

value Y) //Preconditions: X and Y have values //Postconditions: Returns the value of the larger of X and Y B1 If X > Y THEN B2 Larger X B3 ELSE B4 Larger B5 ENDIF B6 RETURN Y .User-defined Functions: Ex. Of Pseudocode function Larger(value X.

1. we designate the value we wish to return by assigning it to the name of the function. Don’t let the idea that a function is different from a subroutine-type module confuse you. You have to make it clear that you are creating a function. Since you’ll be using the function name inside an expression in the calling module. 3. 2. . so the keyword function precedes the module name. A function is still a module. The parameters are both passed by value. A function is a module.

.

.

. like C and C++. functions are the only module type—there are no subroutines. They used subroutines when they want to return more than one value. with the value returned by one function serving as the parameter for another. As long as the parameter is a value parameter that is no problem. In general. that is. many programmers use functions when they want to return a single value and/or they want to use the function in an expression or output statement. In some languages.Sometimes you even wind up with functions inside functions.