mod array para

Upload: kamugasha-kagonyera

Post on 06-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Mod Array Para

    1/77

    Subroutines:

    We are basically done going over the three controls structures ofprogramming: sequential, conditional and loop. This means that we haveall the tools we need to write any program.

    There are however, other features to make programming better (moreefficient). These two features (for us) are subroutines and arrays.Subroutines (and probably arrays) are the difference between a goodprogram and a bad program.

    Subroutines consist of breaking up a problem into smaller parts and thensomehow putting them together again.

  • 8/3/2019 Mod Array Para

    2/77

    Subroutines (the 2nd

    hardest topic of the semester)

    Subroutine Syntax

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

    Our simple three-line program:

    INPUT a, b, c

    sum = a + b + cDISPLAY sum

    The best way to represent this program, using subroutines, is to use astructure chart.

  • 8/3/2019 Mod Array Para

    3/77

    MAIN

    INPUTS

    CALC

    PRINT

    Using subroutines this program is really broken down into four separateprograms with main as the boss program.

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

    (1) MAIN

    A1 Call INPUTSA2 Call CALC

    A3 Call OUTPUTA4 END

    (2) INPUTS

    B1 INPUT a, b, cB2 RETURN

    (3) CALC

    C1 sum = a + b + cC2 RETURN

  • 8/3/2019 Mod Array Para

    4/77

    (4) OUTPUT

    D1 DISPLAY sumD2 RETURN

    Note: The use of RETURN at the end of each separate program thisreturns it to the MAIN.

    StatementNumber

    a b c sum Output

    A1

    B11

    2 3

    B2

    A2

    C1 6

    C2

    A3

    D1 6

    D2

    A4

  • 8/3/2019 Mod Array Para

    5/77

    Communication between modules

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

    1. In our subroutine for input, INPUTS doesnt need anythingfrom 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 fromMAIN and needs to send the value of sum back to MAIN.3. OUTPUT needs the value of sum from MAIN.

  • 8/3/2019 Mod Array Para

    6/77

    Note: These concepts about communication are a very important conceptto 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 everymodule 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.

  • 8/3/2019 Mod Array Para

    7/77

    2. Local Variables it is also possible to declare a variable as a

    local variable within a particular module. These variables aretreated in the same old way that you are used to, as long as youare executing the statements within that particular module. Thelocal variable does not exist as far as the other modules areconcerned.

    Lets change 2 lines of our present program:

    MAIN

    Call INPUTSCall CALCCall OUTPUTEND

    INPUTS

  • 8/3/2019 Mod Array Para

    8/77

    INPUT a, b, cRETURN

    CALC

    temp = a + bsum = temp + cRETURN

    OUTPUT

    DISPLAY sumRETURN

    Did you find the new line?

    This variable isnt a global variable like the other variables. It is a localvariable. It shouldnt and isnt known by the other subroutines. It OUTPUTwere to use temp as a variable, it couldnt be processed (syntax error). Ithasnt been declared.

  • 8/3/2019 Mod Array Para

    9/77

    Here is the same problem written in Visual Basic:

    Option explicit

    declare global variablesdim a as integer

    dim b as integerdim c as integerdim sum as integer

    Notice temp has not been declared here. That is because temp is a localvariable. This is only where global variables are declared.

  • 8/3/2019 Mod Array Para

    10/77

    Private sub cmdMain_click()

    call INPUTS ()call CALC ()call OUTPUT ()End Sub

    _______________________________________________________Sub INPUTS () To get this, hit the key.

    a = inputbox ()b = inputbox ()c = inputbox ()End Sub In Visual this is our RETURN

    _______________________________________________________

    Sub Calc ()

    dim temp as integertemp = a + bsum = temp + cEnd Sub

    _______________________________________________________Sub OUTPUT () OUTPUT can echo the variables. They are global.

    Print sumEnd SubNote: Take careful note of our CALC subroutine. Notice that the tempvariable isnt available to the other subroutines, let alone available to echo.Temp is a local variable that is there only to insure that information isntshared.

    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 globalvariable location. If it is not found there, then that will come up as a syntaxerror. The variable would be undeclared.

  • 8/3/2019 Mod Array Para

    11/77

    Ex. Subroutine using a loop:

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

    Dodgers = 0Giants = 0totalinnings = 4For innings = 1 to totalinningsINPUT score

  • 8/3/2019 Mod Array Para

    12/77

    Dodgers = Dodgers + scoreINPUT scoreGiants = Giants + scoreENDFORDISPLAY Dodgers, Giants

    Now, we have to change this program slightly, because the teams areplaying 3 games this weekend!!! We will need a loop that goes 3 times. Toput the icing on the cake, we want a grand total for each team. This couldpresent a change, but it would take place outside the loop.

    How would you alter the previous program to accomplish the change? Youwould probably need to create several different loops.

    But alas, we dont need to worry about all those loops. We can usesubroutines!!!!!!!!

    The previous program will be our subroutine Play1Game.

    MAIN

    NumGames = 3DodgersGrandT = 0GiantsGrandT = 0FOR game = 1 to NumGamesCALL Play1GameDodgersGrandT = Dodgers GrandT + Dodgers

  • 8/3/2019 Mod Array Para

    13/77

    GiantsGrandT = GiantsGrandT + GiantsENDFORDISPLAY DodgersGrandT, GiantsGrandT

    Play1Game

    Dodgers = 0Giants = 0totalinnings = 4For innings = 1 to totalinningsINPUT scoreDodgers = Dodgers + scoreINPUT scoreGiants = Giants + score

    ENDFORDISPLAY Dodgers, Giants

    This program works more efficiently. This type of approach is needed with alarge program. The only problem that exists is that totalinnings = 4 in ourPlay1Game should be moved to our MAIN program so it wouldnt have tobe executed numerous times. Also, we want to keep all of our constantsat 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 inturn, Play1Game needs totalinnings from the MAIN program. THIS ISVERY IMPORTANT. IT WILL HAUNT YOU LATER.

  • 8/3/2019 Mod Array Para

    14/77

    Design

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

  • 8/3/2019 Mod Array Para

    15/77

    The Process of Design

    There are two approaches:

    1. Top-down functional design2. Object-oriented approach (which is used more often)

    Guidelines:

    The most important guideline that we should concentrate on is this: EACHSUB-PROGRAM SHOULD CORRESPOND TO SOME EASY-TO-UNDERSTAND, INDEPENDENT TASK OR PROBLEM

  • 8/3/2019 Mod Array Para

    16/77

    1. Task oriented approach Step-wise refinement. Modulardecomposition.2. Object-oriented approach looks at the problem anddecomposes it into the various objects that comprise theproblem. The designer must consider the data to represent thestate of each object and the behavior that each object might beexpected to exhibit. For example: representing a customermight require data such as name, address and phone number,and behaviors like buying a book, ordering a book, and makingsome sort of inquiry about books. In the object-oriented

    approach, the designer would design a customer object, whichcontains both the data and the behaviors.

  • 8/3/2019 Mod Array Para

    17/77

    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

  • 8/3/2019 Mod Array Para

    18/77

    Team Average (4 bowlers each)

    200

    First off, lets calculate the average of each bowler. Second, we need tocalculate a team average.

    ********THE KEY: WHAT INFORMATION DOES EACH LEVELNEED?********

    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 itsimple!! We could also have Bowling display individual averages and the

  • 8/3/2019 Mod Array Para

    19/77

    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 choosesglobal.

    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 = 3numbowlers = 4CALL CalcAverage1Bowler

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

  • 8/3/2019 Mod Array Para

    20/77

    computer and ourselves.

    MAIN

    numgames = 3numbowlers = 4FOR bowlers = 1 to numbowlersCALL CalcAverage1Bowlersum = sum + avg

    ENDFORCALL CalcTeamAverageEND

    CalcAverage1Bowler (segment):

    Tasks:1. get scores, add scores2. divide

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

  • 8/3/2019 Mod Array Para

    21/77

    Note: Usually, we make constants global, but in this case, we will makethem local for convenience sake.

    CalcAverage1Bowler

    totscore = 0FOR scores = 1 to numgamesCALL Get1ValidScoretotscore = totscore + score

    ENDFOR

    avg = totscore / numgamesRETURN

    Calc.Average

    Get Scores&

    Add Scores

    Divide

    GetValidScore segment:

  • 8/3/2019 Mod Array Para

    22/77

    GetValidScore

    INPUT scoreWHILE score < 0 or score >300INPUT score

    ENDWHILERETURN

    Note: There are local constants here!!!

    Are there any values in MAIN that are not shared? No, in MAIN allvariables are global.

    The three secrets of Designing good modules:

  • 8/3/2019 Mod Array Para

    23/77

    Secret 1: Always decompose problems based on tasks. Then determinethe sub-tasks that need to be done for each of the tasks. Make thosemodules. Keep going until the tasks are small enough to attack at thepseudocode level.

    Secret 2: When designing and implementing modules, make them blackboxes. Make sure your module has no unintended side effects. In thepreconditions and post conditions make sure each module provides all ofthe information needed to use the module.

    Secret 3: When using modules practice abstraction.

    THINGS TO REMEMBER:

  • 8/3/2019 Mod Array Para

    24/77

    1. Modules can call other modules. The MAIN modules are notthe 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

  • 8/3/2019 Mod Array Para

    25/77

    Here is the problem:

    I want to write an algorithm that adds up 3 different numbers and prints theaverage. Then, I want to print the difference between each number and theaverage.

    Ex:

    For the variables of 6, 5, and 1. I want to find the difference between 6 and4, 5 and 4, and 1 and 4.

    For the algorithm we have:

    INPUT a,b,cSum = a + b + cAvg = Sum / 3DISPLAY a AvgDISPLAY b AvgDISPLAY c AvgEND

    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

  • 8/3/2019 Mod Array Para

    26/77

    FOR x = 1 to maxINPUT numsum = sum + num

    ENDFORAvg = sum / maxEND

    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:

  • 8/3/2019 Mod Array Para

    27/77

    Numbers

    (1) 5

    (2) 3

    (3) 9(4) 2

    (5) 8

    Referring to values in the array:

    Numbers(1)= 5Numbers(1+4)=8

    In Visual Basic the declarations will be:// declare an array called Numbers that holds 5 integersConst Max=5;Dim Numbers (Max) as Integer

  • 8/3/2019 Mod Array Para

    28/77

    But, we need to be able to use each individual slot! What can we do? We use asubscript 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, butoutside of the declarations statement, it means (Numbers(5)) memory location 5that is within Numbers.

    Continuing on from our initial dim statement, here are some examples of theway an array works!

    Fun with Arrays

    max = 5dim 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)

  • 8/3/2019 Mod Array Para

    29/77

    Numbers(4) = Numbers(3) 1 (location 4 gets 20)

    Print Numbers(4 + 1) + 1 (this displays 38)x= 3y = 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 1Print Numbers(x) (this displays 21)

    Here are some more examples (potential test questions) using the above memorylocation values.

    Print Numbers(x y) (This would result in an error. There is noNumbers(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, printthe average, and then print the difference between each variable and the average.

    max = 3sum = 0FOR x 1 to maxINPUT num(x)sum = sum + num(x)

    ENDFORavg = sum / max

    FOR y 1 to max

    DISPLAY num(y) avgENDFOREND

    Where do all the numbers get input? In num(x)

  • 8/3/2019 Mod Array Para

    30/77

    Note: is this confusing?

    Be able to declare arrays and perform desk checking algorithmscontaining 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 isreferring to the Grades arrays first element

    Subscript Names Subscript Grade

    (1) Joe

  • 8/3/2019 Mod Array Para

    31/77

    (2) Mary

    (3) Hal

    (4) Phil

    (5) Anne

    (1) 80

    (2) 90

    (3) 77

    (4) 93

    (5) 81

    The idea is when the user enters the name Hal, it should display 77. Therefore weneed to determine which subscript corresponds to a particular name.

    Here is our structure chart for this problem:

  • 8/3/2019 Mod Array Para

    32/77

    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.

  • 8/3/2019 Mod Array Para

    33/77

    //postconditions: The Grades element corresponding to the targetis displayed location contains the subscriptwhere target was found.

    Program pseudocode:

    MAIN

    sentinel = -99max = 5CALL GetDataINPUT Target //priming readWHILE Target sentinelCALL FindAScore

    INPUT TargetENDWHILEEND

    GetData (This is the easy one!!!)

    FOR I 1 to MaxINPUT Names(I)

    INPUT Score(I)ENDFORReturn

    FindAScore This is the had one!!!!!

    FOR I = 1 to maxIF Names(I) = TargetDISPLAY Score(I)

    ENDIFENDFOR

  • 8/3/2019 Mod Array Para

    34/77

    Return

    Note : All right this works, but there is a problem. This program will gothrough all the loops even if the score is found at the beginning. Weneed a smarter loop to be more efficient. We also need something thatwill 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

  • 8/3/2019 Mod Array Para

    35/77

    // target is displayed and Found is T, if there is // // no match, the message not found is displayed // and Found is F

    FindAScore

    found FIndex1WHILE Index

  • 8/3/2019 Mod Array Para

    36/77

    Index = max + 1ENDIF

    ENDFORIF Found = F THENDISPLAY Not Found

    ENDIFReturn

    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

    445

    93

    1) it took one less than number of elements in array2) the smallest value has not made it to the top.

  • 8/3/2019 Mod Array Para

    37/77

    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 thatloop will have n-1 iterationsWe also need an outer loop to force the inner loop go n-1 times

    FOR i 1 to n-1 // outer loopFor j 1 to n-1 // inner loop

    Compare elements and swap if neededENDFORENDFOR

    FOR i 1 to n-1 // outer loopFOR j 1 to n-1 // inner loop

    IF Values(j)> Values(j+1) THENTempValues(j)Values(j) Values(j+1)Values(j+1)Temp

    ENDIFENDFOR

    ENDFOR

    Two problems: compares all the way to the end every timeDoes not care if the array is already sorted

    First Improvement:-Two Way Bubble SortThe first time through the loop we want to compare all the way to the lastelement.(compare element(n-1) to element(n))

  • 8/3/2019 Mod Array Para

    38/77

    The second time, we only go as far as comparing element(n-2) with element(n-1) andon the next one compare element(n-3) with element (n-2).Therefore,For i 1 to n-1

    For j 1 to n-iIF Values(j)> Values(j+1) THEN

    TempValues(j)Values(j) Values(j+1)Values(j+1)Temp

    ENDIFENDFOR

    ENDFOR

    Second improvement: Bubble Sort with FlagEven with Two- Way bubble sort, we still have the problem of not caring whether thearray id already sorted.So we need a flag to tell us if any swaps were there.

    SortedFWHILE Sorted =F

    Sorted- T // set for inner loopFOR i 1 to n-1FOR j 1 to n-i

    IF Values(j)> Values(j+1) THENSortedFTempValues(j)Values(j) Values(j+1)Values(j+1)Temp

    ENDIFENDFOR

    ENDFORENDWHILE

    Here is a scenario:

    We have five teams and want to enter each team and the number ofgames that they have won into two different arrays.

    Here is the algorithm:

    max = 5FOR x = 1 to maxINPUT teams(x)INPUT games(x)

  • 8/3/2019 Mod Array Para

    39/77

    ENDFOREND

    Teams and games use the same subscript. Therefore, they are parallelarrays.

    Now we need to sort from highest to lowest number of games won:

    FOR I 1 to max 1FOR j = 1 to max 1IF games (j) < games(j + 1) THENtemp = games (j)games(j) = games (j + 1)games(j + 1) = temp

    temp2 = teams(j)teams(j) = teams(j + 1)teams(j + 1) = temp2ENDIF

    ENDFORENDFOR

    Note: Notice that we cant use the same variable name (temp) for gamesas we use for teams. That is because one is a string and one is anumber.

    Explanation of the two loops within this program:

    For I = 1 to max 1

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

  • 8/3/2019 Mod Array Para

    40/77

    ******The max 1 in the I loop is there, because (max = 5) tocompletely 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 bubblesort works, we compare the value of one slot with the next value in thearray. This means that when we reach slot #5, we dont want to compareit to the next value. The next value would be garbage! Thus, we need amax 1 in there.

    (1) 162

    (2) 189

    (3) 159

    (4) 200

    (5) 197

    How would we change our program to DISPLAY the worst team to thebest? (Considering that the array is already sorted from highest to

  • 8/3/2019 Mod Array Para

    41/77

    lowest)

    Like this:

    h = maxWHILE h >= 0DISPLAYh = h 1ENDWHILE

    Note: This is only a part of the program, but it is the only part that wewould need to change.

    Okay, How would you change it to DISPLAY the games won of aparticular INPUT team:

    INPUT targetFOR I = 1 to maxIF teams(i) = target THEN

    DISPLAY games(i)ENDIFENDFOR

    Using a WHILE loop:

    INPUT targetI = 1WHILE I

  • 8/3/2019 Mod Array Para

    42/77

    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 searchalgorithm called binary search.

    1 5

    2 12

    3 19

    4 54

    5 986 112

    7 144

    8 200

    9 242

    10 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 target3. 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 array4. we need to look for the top half (1+4)/ 2 5/2= 2.5 take the integer part 25. is numbers(2) = to target? No6. look to see if the numbers(2) is greater than target? No7. 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 39. 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.

  • 8/3/2019 Mod Array Para

    43/77

    Desk checking algorithms that contain arrays:

    1 max 32 FOR Ind 1 to max

    3 nums(Ind) Ind * 104 ENDFOR5 Ind max6 WHILE Ind > 07 DISPLAY numbs(Ind)8 Ind Ind 19 ENDWHILE10 END

  • 8/3/2019 Mod Array Para

    44/77

    Expected Input List: NoneAvailable Output List: 30,20,10

    StatementNumber

    Output

  • 8/3/2019 Mod Array Para

    45/77

    Learning to Share

    Top-Level Design involves two related tasks:

    1.The act of decomposing a problem intopieces.2.Determining how the various piecesshould communicate with each other.

    The subject of this chapter is the second task.

  • 8/3/2019 Mod Array Para

    46/77

    In the earlier chapter, modules communicatedusing global variables and this method workedjust fine. Every variable had a name and everymodule had access to each variable.

    The danger of this is that one module may changethe value of a variable, which another module wasusing. Such an error is devastating to the logicof the program and is also very hard to locate.

    Local and global variables:

    1.A global variable is one, which isavailable to all modules.2.A local variable is one, which is onlyused within a module and is not availableto any other module.

    Two ways that modules can share data:

    1.Use of global variables.2.Use of parameters.

  • 8/3/2019 Mod Array Para

    47/77

    Try to consider throughout this chapter how localvariables, and especially parameters, contributeto the idea of writing and using black boxmodules (with information hiding).

    There are many variables in a large program,That is only needed by one module. By makingsuch variable local, you take away thepossibility that some other module(being writtenby another team) might change the value storedthere.

  • 8/3/2019 Mod Array Para

    48/77

    What is a side-affect? A side-affect is something within the entireprogram that gets affected within a subroutine. This usually occurswhen using global variables.

    Because of these side-affect, parameters are used in place of mostglobal variables.

  • 8/3/2019 Mod Array Para

    49/77

    Parameters

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

  • 8/3/2019 Mod Array Para

    50/77

    Parameters (last, most difficult topic for thesemester)

    Here is a sample, non-sense, terrible program (toprove a point):

    MAIN

    INPUT nCall AddemupCall TemperaturesPrint n, sum, avetemp

  • 8/3/2019 Mod Array Para

    51/77

    END

    Addemup

    sum = 0FOR i 1 to nsum= sum + nENDFORReturn

    AveTemp

    sum = 0INPUT nFOR i 1 to nINPUT tempsum = sum + tempENDFOR avetemp = sum / nReturn

    Why doesnt this program work worth a darn?

    1. Which variables are global?

    a. sum, avetemp and n a global variables. But sum getschanged in 2 or the subroutines, and so does n. Thisprogram is a mess.b. Its to easy for somebody to step on someone elses

    global variables! Dont get me wrong global constantsare a good thing.

    When we need to share what do we do?

  • 8/3/2019 Mod Array Para

    52/77

    Structure chart for our NON-Sense Program using parameters:

  • 8/3/2019 Mod Array Para

    53/77

    n sum

    sum AveTemp

    Note the arrows. These arrows are actuallyparameters!

  • 8/3/2019 Mod Array Para

    54/77

    Main

    AveTemp

    AddemupThis is the famous Happy Birthday Program

    Happy

    FOR i 1 to 2DISPLAY Happy Birthday to you

    ENDFORDISPLAY Happy Birthday, Dear ___________DISPLAY Happy Birthday, to youReturn

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

  • 8/3/2019 Mod Array Para

    55/77

    First Way: //Global Person

    Person = FredCALL HappyPerson = Mary

    CALL Happy

    Happy

    FOR i 1 to 2DISPLAY Happy Birthday to you

    ENDFORDISPLAY Happy Birthday, Dear ___________DISPLAY Happy Birthday, to youReturn

  • 8/3/2019 Mod Array Para

    56/77

  • 8/3/2019 Mod Array Para

    57/77

    Main

    //local variable person

    Person = FredCALL Happy(Person) //This sends thevalue ofperson toHappy

    DISPLAY Person //Displays FredPerson = Mary

    Call Happy(Person)END

    Happy(value parameter person)

    FOR i 1 to 2DISPLAY Happy Birthday to you

    ENDFORDISPLAY Happy Birthday, Dear ___________DISPLAY Happy Birthday, to you

    Person = huhDISPLAY Person //Displays huhReturn

  • 8/3/2019 Mod Array Para

    58/77

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

    Main

    //local variable personPerson = Fred

    CALL Happy(Person) //This sends thevalue ofperson toHappy

    DISPLAY Person //Displays FredCALL Happy(Mary)

    INPUT OtherCALL Happy(Other)END

    Note: Check out the statement CALLHappy(Mary). The actual value inside thequotes gets sent to Happy. If we took out thequotes, What would happen? We would send merelygarbage, because we havent given a value to thatparticular place in memory!! Get it????

  • 8/3/2019 Mod Array Para

    59/77

    New Scenario:

    INPUTs: 7,2

    Main

    INPUT a, b //local variablesCALL Diff(a,b)DISLAY a //Displays 7END

    Diff (value a, value b)//2 parameters

    a = a bDISPLAY aReturn

  • 8/3/2019 Mod Array Para

    60/77

    Similarly:

    INPUTs: 7,2

    Main

    INPUT a, b //local variablesCALL Diff(6,9)DISLAY a //Displays 7END

    Diff (value a, value b)//2 parameters

    a = a bDISPLAY a //Displays -3Return

  • 8/3/2019 Mod Array Para

    61/77

    INPUTs: 7,2

    Main

    INPUT a, b //local variablesCALL Diff(b,a)

    DISLAY a //Displays 7END

    Diff (value a, value b)//2 parameters

    a = a bDISPLAY a //Displays -5Return

    Have you figured out why????

    Yep! What maters is the order that the valuesare sent.

  • 8/3/2019 Mod Array Para

    62/77

    INPUTs: 7,2

    Main

    INPUT a, b //local variablesCALL Diff(a,b,sum)

    DISLAY sum //Displays 5END

    Diff (value a, value b, reference sum)

    sum = a bDISPLAY sumReturn

    Note: Pay attention to where we defined ourparameters: Sub Diff(value a, value b, referencesum). This new addition the reference additionis equivalent to an up arrow. It sends the valueof sum back up to Main.

  • 8/3/2019 Mod Array Para

    63/77

    INPUTs: 6,2

    Main

    // local variables a,b,cINPUT a, b //local variablesCALL Diff(a,b,c)DISLAY c //Displays 4

    END

    Diff (value a, value b, reference sum)

    sum = a bReturn

    When you use parameters, the association of aparameter in the calling module is call the

    actual argument.

    The parameter in the called module is called theformal parameter or sometimes the dummy parameter

  • 8/3/2019 Mod Array Para

    64/77

    Points to Ponder:

    Structure Charts

    a) Structure charts show the modules of a system, and theyshow the parameter-based communication between thosemodules.b) The straight lines joining two boxes on the chart are

    invocation lines, that is, they indicate that one box calls theother.c) Calling modules are always higher up on the page thanthe modules they call. As a result the invocation lines dontneed arrows.d) Data couples represent information that must be sharedbetween modules. Data couples use little arrowheads toshow 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 notshow up on a structure chart.

  • 8/3/2019 Mod Array Para

    65/77

    Data Couples- A data couple represents a single data item that isbeing shared or a data couple represents a parameter.

    A data couple is represented by an arrow on a structure chart (it hasa circle at one end and an arrow head at the other).

    SumNum1 Num1 Num2

    Num2

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

  • 8/3/2019 Mod Array Para

    66/77

    ****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 isbeing communicated up to the calling module.

    Calculate Sum

    Get Input

    Main

    The down-arrow couples carry information that isneeded in the called module, but was createdsomewhere else. That information must be in thepossession of the calling module.

  • 8/3/2019 Mod Array Para

    67/77

    1.Any data couple on the structure chart,which points down only is implemented as avalue-type parameter.2.Any data couple on the structure chartwhich points up, and that includes the ones

    that point down and up is implemented as areference-type parameter in mostprogramming languages.3.The difference between up and down andup data couples is purely logical for mostprogramming endeavors. The couples provideimportant information to designers, testers,maintenance programmers and others.

    However, the actual coding treats both ofthose couples the same.

  • 8/3/2019 Mod Array Para

    68/77

    Top-Level Design Using Parameters:

    1.First, we decompose the problem intosmaller problems.2.Even before considering any further sub-division of any of the modules, you can

    establish the necessary data couples. Thatis you can figure out what informationneeds to be shared, between whom and inwhat direction.

  • 8/3/2019 Mod Array Para

    69/77

    The pseudocode syntax for parameter passing:

    1.In the declaration for the called module, thename of the module is followed by openingparentheses. Then the keyword reference is

    included. Then, after a space, we have thename of the parameter. Then the parenthesesare closed.2.In the calling module, when the module iscalled, you include just the name of theparameter you are passing, in parentheses.

  • 8/3/2019 Mod Array Para

    70/77

    Functions:

    A function is a special case of the general conceptof a module.

    A function is a module, which returns a value.

    A subroutine (procedure) gets called by the callingmodule as a single instruction. A function getscalled by using the function directly in anexpression.

  • 8/3/2019 Mod Array Para

    71/77

    Back to absolute value:

    Main ModuleINPUT NumberCALL Calculate_Absolute_Value(Number,Answer)

    DISPLAY AnswerEND

    Calculate_Absolute_Value (value N, reference A)//Preconditions: N contains a value//Postconditions: A returns the absolute value of NIF N < 0 THEN

    A N*(-1)

    ELSEA N

    ENDIF

  • 8/3/2019 Mod Array Para

    72/77

    RETURN

    As a function:

    Main ModuleINPUT Number

    Answer abs(Number)

    DISPLAY AnswerEND

    The function named abs() takes whatever value is

    passed to it and calculates the absolute value.

    Most programming languages provide a wealth of built-in functions.

    Ex.Round a numberCalculate sineCalculate cosineCalculate tangentSquare Root

    Lesson: If youve got something you want to do, and it

    seems like something someone else might have wantedto do one, look at the functions available in yourlanguage to see if maybe someone already wrote it foryou.

  • 8/3/2019 Mod Array Para

    73/77

    User-defined Functions:

    Ex. Of Pseudocode

    function Larger(value X,value Y)//Preconditions: X and Y have values

    //Postconditions: Returns the value of the largerof X and YB1 If X > Y THENB2 Larger X

    B3 ELSEB4 Larger Y

    B5 ENDIFB6 RETURN

  • 8/3/2019 Mod Array Para

    74/77

    1.You have to make it clear that you arecreating 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 nameinside an expression in the calling module, wedesignate the value we wish to return byassigning it to the name of the function.

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

  • 8/3/2019 Mod Array Para

    75/77

  • 8/3/2019 Mod Array Para

    76/77

  • 8/3/2019 Mod Array Para

    77/77

    Sometimes you even wind up with functions insidefunctions, that is, with the value returned by one functionserving as the parameter for another. As long as theparameter 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 thefunction in an expression or output statement. They usedsubroutines when they want to return more than one value.In some languages, like C and C++, functions are the onlymodule typethere are no subroutines.