You are on page 1of 77

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

sum

Output

Communication between modules

There are a few points to discuss in regards to this aspect of our subroutined program.

1. In our subroutine for input, INPUTS doesnt need anything from MAIN, but INPUTS need to give / send the values of a, b, and c to MAIN. 2. Our CALC subroutine needs the values of a, b, and c from MAIN and needs to send the value of sum back to MAIN. 3. OUTPUT needs the value of sum from MAIN.

Note: These concepts about communication are a very important concept to understand. So learn and understand the concept behind them!

Global Variables

There are 2 ways to share data in subroutines: 1. Global Variables you are telling the translator that every module can retrieve from or store to the variable using the name. There are good reasons for using very few, if any global variables in a program.

2. Local Variables it is also possible to declare a variable as a local variable within a particular module. These variables are treated in the same old way that you are used to, 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.

Lets change 2 lines of our present program:

MAIN Call INPUTS Call CALC Call OUTPUT END

INPUTS

INPUT a, b, c RETURN

CALC temp = a + b sum = temp + c RETURN

OUTPUT DISPLAY sum RETURN

Did you find the new line?

This variable isnt a global variable like the other variables. It is a local variable. It shouldnt and isnt known by the other subroutines. It OUTPUT were to use temp as a variable, it couldnt be processed (syntax error). It hasnt been 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. That is because temp is a local variable. This is only where global variables are declared.

Private sub cmdMain_click() call INPUTS () call CALC () call OUTPUT () End Sub _______________________________________________________ Sub INPUTS () To get this, 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. They are global. Print sum End Sub Note: Take careful note of our CALC subroutine. Notice that the temp variable isnt available to the other subroutines, let alone available to echo. Temp is a local variable that is there only to insure that information isnt shared.

The first place that a program will look for a variable is within its own subroutine. Then, if the variable isnt found, it will look for it in the global variable location. If it is not found there, then that will come up as a syntax error. The variable would be undeclared.

Ex. Subroutine using a loop:

We need a program that will keep the score of a baseball game. This will only be a 4-inning baseball game. We will need to use two variables and a loop that goes 4 times.

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

Now, we have to change this program slightly, because the teams are playing 3 games this weekend!!! We will need a loop that goes 3 times. To put the icing on the cake, we want a grand total for each team. This could present a change, 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.

But alas, we dont need to worry about all those loops. 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, 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. This type of approach is needed with a large program. The only problem that exists is that totalinnings = 4 in our Play1Game should be moved to our MAIN program so it wouldnt have to be executed numerous times. Also, we want to keep all of our constants at the beginning of our MAIN program. 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. THIS IS VERY IMPORTANT. IT WILL HAUNT YOU LATER.

Design

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

The Process of Design

There are two approaches: 1. Top-down functional design 2. 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, INDEPENDENT TASK OR PROBLEM

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

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 (4 bowlers each) 200

First off, lets calculate the average of each bowler. Second, we need to calculate a team average. ********THE KEY: WHAT INFORMATION DOES EACH LEVEL NEED?********

We have 3 different levels at the moment: 1. Bowling (the president) 2. Calc. Average 1 bowler (the vice-president) 3. Calc. Team Average (the second vice-president)

Calc. Team Average should get the total of all averages. This is to keep it simple!! We could also have Bowling display individual averages and the

team averages, but we will let the middle management handle it. REMEMBER: Design is a matter of decision.

Should numgames be a global or a local variable? The professor chooses global. 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. Team Average, because it is only one line, but we will do it this way for now.

The Presidents Job (Bowling)

MAIN numgames = 3 numbowlers = 4 CALL CalcAverage1Bowler

Whats wrong with this? We need a loop or we will create more work for the

computer and ourselves.

MAIN numgames = 3 numbowlers = 4 FOR bowlers = 1 to numbowlers CALL CalcAverage1Bowler sum = sum + avg ENDFOR CALL CalcTeamAverage END

CalcAverage1Bowler (segment): Tasks: 1. get scores, add scores 2. divide

Here is our structure chart, so far for this segment:

Note: Usually, we make constants global, but in this case, we will make them local for convenience sake. CalcAverage1Bowler totscore = 0 FOR scores = 1 to numgames CALL Get1ValidScore totscore = totscore + score ENDFOR avg = totscore / numgames RETURN

Calc. Average Get Scores & Add Scores

Divide

GetValidScore segment:

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, in MAIN all variables are global.

The three secrets of Designing good modules:

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

THINGS TO REMEMBER:

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

Arrays

Here is the problem: I want to write an algorithm that adds up 3 different numbers and prints the average. Then, I want to print the difference between each number and the average. Ex: For the variables of 6, 5, and 1. I want to find the difference between 6 and 4, 5 and 4, and 1 and 4.

For the algorithm we have: INPUT a,b,c Sum = a + b + c Avg = Sum / 3 DISPLAY a Avg DISPLAY b Avg DISPLAY c Avg END Okay, this is fine, but what if we want to do the same with 300 numbers?

Well, we can do this using a loop: max = 300

FOR x = 1 to max INPUT num sum = sum + num ENDFOR Avg = sum / max END Okay, were 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. We can use and array.

Ex: This is what our memory location looks like:

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

But, 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), Numbers(2), and etc. Note: The dim (declaration statement) means that Numbers(Max) has 5 locations, but outside of the declarations statement, it means (Numbers(5)) memory location 5 that is within Numbers.

Continuing on from our initial dim statement, 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)

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. They are separate variables.) 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. Print Numbers(x y) (This would result in an error. There is no Numbers(0)) Print Numbers( x + y + 10) (This would also result in an error. Numbers(14) doesnt exist.) Numbers(x) = 5 (Numbers(2) gets 5) Print Numbers(Numbers(y)) (Displays 37. This is the profs Favorite question.) *******************************************************************************

Now, back to our first problem. Remember that we wanted to add up our numbers, print the average, and then print the difference between each variable and the average. 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)

Note: is this confusing? Be able to declare arrays and perform desk checking algorithms containing arrays

Be familiar with concept of Parallel Arrays, with Sequential Search

Ex: The Problem: We want to input a students name and print out their final exam grade. Finding the students grade when we enter the name. We declare two arrays, one to hold the names, other one to hold grades. We keep these two in parallel, so the Names arrays first element is referring to the Grades arrays first element

Subscript (1) Joe

Names

Subscript

Grade

(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, it should display 77. Therefore we need to determine which subscript corresponds to a particular name.

Here is our structure chart for this problem:

1. What information does GetData need? 2. What does FindAScoreneed? 3. What does Main need?

Main
FindAScore

GetData

Search for Student Grade: // 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: 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

Return Note : All right this works, but there is a problem. This program will go through all the loops even if the score is found at the beginning. We need a smarter loop to be more efficient. We also need something that will tell us that the Target isnt in our index.

// 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, // then the Grades element corresponding to the

// // // FindAScore

target is displayed and Found is T, if there is // no match, 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 FoundT 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

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.

3) In this worst-case the smallest number has only moved one step up.

22 5 44 93 5 22 44 93
This algorithm will need two loops, 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.(compare element(n-1) to element(n))

The second time, 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). Therefore, 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- Way bubble sort, we still have the problem of not caring whether the array id already sorted. So we need a flag to tell us if any swaps were there. SortedF 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 SortedF 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. Here is the algorithm: max = 5 FOR x = 1 to max INPUT teams(x) INPUT games(x)

ENDFOR END Teams and games use the same subscript. Therefore, they are parallel arrays. 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 cant use the same variable name (temp) for games as we use for teams. That is because one is a string and one is a number.

Explanation of the two loops within this program:

For I = 1 to max 1 FOR j = 1 to max 1 -----------------------------------------------------------------------etc------

******The max 1 in the I loop is there, because (max = 5) to completely sort the array, we need to loop through it 4 times (not 5). The max 1 in the j loop is because, considering the way the bubble sort works, we compare the value of one slot with the next value in the array. This means that when we reach slot #5, we dont want to compare it to the next value. The next value would be garbage! Thus, we need a max 1 in there.

(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

lowest)

Like this: h = max WHILE h >= 0 DISPLAY h=h1 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

Expected Input List: None Available Output List: 30,20,10

Statement Number

Output

Learning to Share

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

In the earlier chapter, modules communicated using global variables and this method worked just fine. Every variable had a name and every module had access to each variable. The danger of this is that one module may change the value of a variable, which another module was using. Such an error is devastating to the logic of the program and is also very hard to locate.

Local and global variables: 1. A global variable is one, which is available to all modules. 2. A local variable is one, which is only used within a module and is not available to any other module.

Two ways that modules can share data: 1. Use of global variables. 2. Use of parameters.

Try to consider throughout this chapter how local variables, and especially parameters, contribute to the idea of writing and using black box modules (with information hiding).

There are many variables in a large program, That is only needed by one module. By making such variable local, 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. This usually occurs when using global variables. Because of these side-affect, 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.

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

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 doesnt this program work worth a darn? 1. Which variables are global? a. sum, avetemp and n a global variables. But sum gets changed in 2 or the subroutines, and so does n. This program is a mess. b. Its to easy for somebody to step on someone elses global variables! Dont get me wrong global constants are a good thing.

When we need to share what do we do?

Structure chart for our NON-Sense Program using parameters:

sum

sum

AveTemp

Note the arrows. parameters!

These arrows are actually

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, Dear ___________ DISPLAY Happy Birthday, to you Return

Yes, thats correct, we want the name of someone to go in the space! How do we get a name in there???

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, 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, to you Return

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, Dear ___________ DISPLAY Happy Birthday, to you Person = huh DISPLAY Person //Displays huh Return

Understand this: Within our subroutine Happy, the value of Person only gets changed within Happy, and it does not get changed in Main.

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). The actual value inside the quotes gets sent to Happy. If we took out the quotes, What would happen? We would send merely garbage, because we havent given a value to that particular place in memory!! Get it????

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

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

INPUTs: 7,2 Main INPUT a, b //local variables CALL Diff(b,a) DISLAY a //Displays 7 END Diff (value a, 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.

INPUTs: 7,2 Main INPUT a, b //local variables CALL Diff(a,b,sum) DISLAY sum //Displays 5 END Diff (value a, value b, reference sum) sum = a b DISPLAY sum Return

Note: Pay attention to where we defined our parameters: Sub Diff(value a, value b, reference sum). This new addition the reference addition is equivalent to an up arrow. It sends the value of sum back up to Main.

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

Points to Ponder: Structure Charts

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

Data Couples- A data couple represents a single data item that is being shared or a data couple represents a parameter. 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).

Num1 Num2

Sum Num1 Num2

The direction of the arrow shows which way the data is going. Some parameters communicate data up, that is from the called module to the calling module. Some parameters communicate data down, from the calling module to the called module. Some go both ways.

****ARROW UP: Reference parameter**** ****ARROW DOWN: Value parameter****

Down- and-up Data Couples: The up-arrow couples carry information that was created in the called module. That information is being communicated up to 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. That information must be in the possession of the calling module.

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

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

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

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

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

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.

Most programming languages provide a wealth of builtin functions. Ex. Round a number Calculate sine Calculate cosine Calculate tangent Square Root Lesson: If youve got something you want to do, and it seems like something someone else might have wanted to do one, look at the functions available in your language to see if maybe someone already wrote it for you.

User-defined Functions: Ex. Of Pseudocode function Larger(value X,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

1. You have to make it clear that you are creating a function, so the keyword function precedes the module name. 2. The parameters are both passed by value. 3. Since youll be using the function name inside an expression in the calling module, we designate the value we wish to return by assigning it to the name of the function.

A function is a module. Dont let the idea that a function is different from a subroutine-type module confuse you. A function is still a module.

Sometimes you even wind up with functions inside functions, that is, 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, 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. They used subroutines when they want to return more than one value. In some languages, like C and C++, functions are the only module typethere are no subroutines.

You might also like