Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3:...

18
Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot) – c 2015 Renske Smetsers-Weeda & Sjaak Smetsers Licensed under the Creative Commons Attribution 4.0 license, https://creativecommons.org/licenses/by/4.0/ 1 Introduction In the previous assignments you have become acquainted with Greenfoot and algorithmic think- ing. You are able to read, modify and write your own code. You also practiced devising generic solutions and implementing them. In this exercise you will learn how to write code in a smarter way. With this cleverness, your solution will be more efficient and more elegant. It also makes it easier to re-use your solution in other situations (in other methods or programs). 2 Learning objectives After completing this assignment, you will be able to: recognize nesting in a flowchart and in code; apply nesting as a strategy for solving problems; optimize a flowchart; modify code according to proposed changes in a flowchart; name benefits of abstraction; identify candidates for sub-methods in a flowchart; apply abstraction in flowcharts and corresponding code by using sub-methods; describe the advantages of designing a program in a structured manner, for example by using a flowchart, on (the types and amount of) implementation errors; determine whether a solution is generic; explain in your own words how the Greenfoot Run works (as a repeating Act); stop a Greenfoot program; write, compile, run and test your own code. 3 Instructions In this assignment you will carry on with your code from assignment 2. Therefore you will need a copy of the scenario which you saved after completing assignment 2, Asgmt2_yourName. To make a copy follow the next steps: Open your scenario from assignment 2, Asgmt2_yourName. In the Greenfoot menu at the top of the screen, select ’Scenario’ and then ’Save As ...’. Check that the window opens in the folder where you want to save your work.

Transcript of Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3:...

Page 1: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Assignment 3: Optimizing solutions

– Algorithmic Thinking and Structured Programming (in Greenfoot) –c©2015 Renske Smetsers-Weeda & Sjaak Smetsers

Licensed under the Creative Commons Attribution 4.0 license,

https://creativecommons.org/licenses/by/4.0/

1 Introduction

In the previous assignments you have become acquainted with Greenfoot and algorithmic think-ing. You are able to read, modify and write your own code. You also practiced devising genericsolutions and implementing them. In this exercise you will learn how to write code in a smarterway. With this cleverness, your solution will be more efficient and more elegant. It also makes iteasier to re-use your solution in other situations (in other methods or programs).

2 Learning objectives

After completing this assignment, you will be able to:

• recognize nesting in a flowchart and in code;

• apply nesting as a strategy for solving problems;

• optimize a flowchart;

• modify code according to proposed changes in a flowchart;

• name benefits of abstraction;

• identify candidates for sub-methods in a flowchart;

• apply abstraction in flowcharts and corresponding code by using sub-methods;

• describe the advantages of designing a program in a structured manner, for example byusing a flowchart, on (the types and amount of) implementation errors;

• determine whether a solution is generic;

• explain in your own words how the Greenfoot Run works (as a repeating Act);

• stop a Greenfoot program;

• write, compile, run and test your own code.

3 Instructions

In this assignment you will carry on with your code from assignment 2. Therefore you will need acopy of the scenario which you saved after completing assignment 2, Asgmt2_yourName. To makea copy follow the next steps:

• Open your scenario from assignment 2, Asgmt2_yourName.

• In the Greenfoot menu at the top of the screen, select ’Scenario’ and then ’Save As ...’.

• Check that the window opens in the folder where you want to save your work.

Page 2: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

• Choose a file name containing your own name(s) and assignment number, for example:Asgmt3_John.

You will also need answer some questions. Questions with an ’(IN) ’ must be handed ’IN’. Forthose you will need:

• pen and paper to draw flowcharts which must be handed in (’(IN) ’),

• a document (for example, Word) open to type in the answers to the ’(IN) ’ questions.

The answers to the other questions (those that don’t need to be handed in) you must discuss withyour programming partner and then jot down a short answer on the assignment paper.

Note: We recommend that you to continue working with your own code. If it is absolutelyimpossible to carry on working with your own code from assignment 2, then you may downloadand use ’DodoScenario3’.

4 Theory

NestingThe language construct for sequence, selection (choice), and repetition can also be usedtogether in various combinations. They can be used sequentially, one after the other, or nestedin each other.

Flowchart:The following is an example of a flowchart of an if .. then .. else statement (selection) nestedin a while loop (repetition).

Figure 1: Flowchart for a selection nested in a repetition

Algorithmic thinking and structured programming (in Greenfoot) 2

Page 3: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

The flowchart explained:

• First the conditional expression ’Check condition1’ in the first diamond is evaluated.

• If the conditional expression is not true, then the ’False’ arrow on the left will be fol-lowed and the method will end.

• If the conditional expression is true, then the ’True’ arrow will be followed to the seconddiamond. The conditional expression ’Check condition2’ will be evaluated.

– If the conditional expression ’Check condition2’ is true, then ’Step2’ will be exe-cuted.

– If the conditional expression ’Check condition2’ is false, then ’Step1’ will be exe-cuted.

• After executing ’Step1’ or ’Step2’, in either case we return to the first diamond (evaluate’Check condition1’). If the expression is still true, then the path to ’Check condition2’will be followed again (loop). If the expression is false, then the method will end.

Code:The corresponding code looks like this:

void methodName( ) { // method with a repetitionwhile ( checkCondition1( ) ){ // check the conditional exp. in diamond

// if the conditional exp. is true, then..if ( checkCondition2( ) ){ // also check cond. exp. in 2nd diamond

// if the 2nd cond. exp. is also true, then..step2 ( ) ; // call the method in the rectangle

} else { // if the 2nd cond. exp. is not true, then..step1 ( ) ; // call the method in the rectangle

}}

}

The code explained:

• First the value of checkCondition1( ) is determined.

• If the conditional statement in the while is false (thus checkCondition1( ) == false), then the method ends.

• If the conditional statement in the while is true (thus checkCondition1( ) == true ),then the conditional statement behind the if is evaluated (thus checkCondition2( ) ).

– If the conditional statement following the if is true (thuscheckCondition2( ) == true ), then the code between the curly brackets {and } is executed (thus step2( ) ).

– If the conditional statement following the if is false (thuscheckCondition2( ) == false ), then the code following the else is executed(thus step1( )).

• After executing step1( ) or step2( ) , in both cases the program jumps back tothe while and the conditional statement in the while is evaluated again (thuscheckCondition1( ) ). If this is still true, we repeat the last few steps and the codebetween the curly brackets is executed again (loop). Otherwise, the method ends.

Note: a sequence, selection or repetition can be used in any order. Any one of them can alsobe used within any other one.

Algorithmic thinking and structured programming (in Greenfoot) 3

Page 4: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

5 Exercises

5.1 Optimizing

OptimizationA flowchart, and its corresponding code, can sometimes be made more efficient, elegant, orclear without affecting how the program works. Such a simplification is called an optimization.An optimization does not affect the operation of the program or final state.

As a result of optimizing the flowchart and code are simplified and often become easier toread, modify (maintain) and test and fewer lines of code are needed. This reduces the chanceof errors.

RedundancyActivities that unnecessarily occur more than once are called redundant.

An example of redundancy:

Figure 2: Flowchart with a redundant activity

In the flowchart in figure 2 ’Step2’ occurs twice.

• If the conditional expression is true, then ’Step 1a’ is executed, followed by ’Step2’;

• If the conditional expression is false, then ’Step 1b’ is executed, followed by ’Step2”;

• After that, the method ends.

In both cases ’Step2’ is executed as a last step. This flowchart can be simplified by combiningthe last two steps together. By doing this, ’Step2’ will only occur once. This simplification hasno effect on how the program works, nor on the final situation. Figure 3 shows the flowchartafter this optimization.

Algorithmic thinking and structured programming (in Greenfoot) 4

Page 5: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

Figure 3: Flowchart without redundant activities

5.1.1 Exercise: removing redundancy

In the following exercises you will practice optimizing redundancy in flowcharts.

Figure 4: Flowchart prior to optimization

1. Have a look at the flowchart in figure 4.

2. Compare the steps in the left path with those in the right. What do you notice?

3. Optimize the flowchart. Make sure your modification does not affect the operation of theprogram or its final state.

4. (IN) Have a look at the flowchart in figure 5. Explain why you can’t do a similar optimiza-tion here.

Algorithmic thinking and structured programming (in Greenfoot) 5

Page 6: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

Figure 5: Flowchart where redundancy optimization is not possible

5.2 Sub-methods

AbstractionA flowchart and its corresponding code can be made clearer by describing a long or complexseries of steps separately. These steps are then described in their own sub-flowchart. Werefer to the new sub-flowchart from the original flowchart. In code, these steps are written ina sub-method. From the method you refer to your new sub-method accordingly. The processof taking details out of the original flowchart or method and describing them separately iscalled abstraction.

Explanation:Abstraction is used in the following cases:

• repetition: if a particular series of steps repeat;

• many steps: when the flowchart becomes unclear and hard to follow by numerousamount of steps (for example: more than seven).

• cohesive set of instructions: if a set of instructions form a fairly independent cohesiveset or module (which may in the future could be re-used elsewhere);

• complex set of instructions: if a set of instructions is so complex that it would be beter(less error-prone) to design, develop and test them separately.

By means of abstraction the code becomes easier to understand, modify and extend. Testingbecomes easier too, because the sub-methods can be tested separately. An error (and itscause) can be found quicker. Because code is not repeated unnecessarily, it is less work andfuthermore less prone to errors. The sub-method can also be re-used in other methodesor even in other programs (possibly by other programmers). Of course, after testing eachsub-method separately, the entire method and program as a whole must be tested.

Example:

Algorithmic thinking and structured programming (in Greenfoot) 6

Page 7: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

Figure 6: Flowchart prior to optimization

Figure 6 shows a flowchart with a few repeating steps. This flowchart can be simplified bymaking a separate sub-method (and sub-flowchart) for these steps. The sub-method is thencalled in the original method. This adjustment has no effect on what the program does or onthe final situation. Figure 7 shows what the flowchart looks like after optimization.

Figure 7: Flowchart after this optimization

5.2.1 Using sub-methods

We are now going to simplify the flowchart from assignment 2 5.3.3 ”Walk around a fence”. Wewill continue to the use the same code.

Algorithmic thinking and structured programming (in Greenfoot) 7

Page 8: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

Figure 8: Flowchart prior to optimization

As with every modification, we will do this step-by-step. This reduces the chance of errors.We will follow the steps for modifying code as explained in assignment 2. Let’s do this togetherthe first time:

1. (IN) Have a look at the flowchart above. Name the sequence of steps (following the ’False’arrow). Which of the Flowchart rules described in assignment 2 are being violated?

2. The first step to using a sub-method is to simplify the flowchart by creating a new sub-flowchart for the long sequence of steps. We will do this in the same manner as in thetheory-block above. The goal is to make a sub-method called ’walkAroundFence’ for thesequence of steps on the right-hand side of the flowchart:

(a) We will place these sequence of steps in a (new) sub-flowchart named WALK AROUNDFENCE (so, having the same name as the sub-method).

(b) From the first flowchart we refer to the new sub-diagram (using a blue dotted line).

(c) The result is shown in figure 9. The new sub-flowchart is shown in green.

(d) (IN) In the flowchart in figure 8, what should be filled in for A, B, and C?

Algorithmic thinking and structured programming (in Greenfoot) 8

Page 9: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

Figure 9: Flowchart act( ) with a call to a sub-method

3. We will now modify the code so that it corresponds to the new flowchart:

(a) Open the ”world eggFenceInWay” world. Use void populateFromFile( ) to do this.

(b) Open the MyDodo code in the editor.

(c) We will make a new sub-method for MyDodo called void walkAroundFence( ). Thiswill correspond to the sub-flowchart ’WALK AROUND FENCE’. Copy the followingcode into MyDodo:

/*** With this method MyDodo ...

*/public void walkAroundFence ( ) {

}

(d) Place all the methods shown in the sub-diagram WALK AROUND FENCE in the codein between the curly brackets { and }. Those are exactly the same steps that you deter-mined in assignment 2 5.3.3 ’Walk around a fence’.

(e) Add comments above the sub-method explaining what it does.

(f) Compile your code.

(g) Drag Mimi into the world and place a fence in front of her.

(h) What do you expect Mimi to do if you call void walkAroundFence( )?

(i) Test your sub-method by right-clicking on Mimi and then selecting void walkAroundFence( ).Does Mimi do exactly what you described in your sub-flowchart?

(j) Remove the fence in front of Mimi.

(k) What do you expect Mimi to do now when you call the void walkAroundFence( ) sub-method?

(l) Test the sub-method void walkAroundFence( ) using this initial situation. Does Mimido exactly what is described in the flowchart?

Algorithmic thinking and structured programming (in Greenfoot) 9

Page 10: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

(m) Now that we have tested the sub-method, we have to call it from the act method, justlike is described in your ’ACT’ flowchart (see figure 9). We modify the act method sothat this calls the new sub-method walkAroundFence when Mimi can’t move (so whencanMove( ) is false). Change the code in void act( ) so that the new sub-method iscalled after the else, thus:

public void act( ){if ( canMove( ) ){

move( ) ;} else {

walkAroundFence( ) ;}

}

(n) Compile, run and test your program by pressing the Act button. By pressing Act younot only test the new walkAroundFence sub-method, but the whole act, so also thecondition ’canMove’ (so Mimi only tries to walk around a fence if she is in front of afence). Test this with and without a fence in front of Mimi. Does the program workas expected? If not, then follow the steps described in the ’Debugging’ theory block inassignment 2.

(o) What do you expect will happen if you call void act( ) several times in a row? Checkthis by pressing the Run button.

4. Save your scenario. Later on (in exercise 5.4) we will come back and keep working on thiscode:

(a) In Greenfoot choose ’Scenario’ from the main menu, and then ’Save As ...’.

(b) Choose a file name containing your own name and assignment number 3a, for exam-ple: Asgmt3a_John.

5.3 Run while you can

RunIf you press the Run button in Greenfoot, then the whole scenario is executed. That meansthat for each actor the act method is continuously executed. This repeats, for each actor,over and over again until you press the Pause button, or until Greenfoot.stop( ) is calledsomewhere in the code.

Flowchart:The flowchart in figure 10 describes the Run behaviour.

Figure 10: Flowchart for Run

The flowchart explained:When the user presses Run, then:

Algorithmic thinking and structured programming (in Greenfoot) 10

Page 11: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

• First the condition expression in the diamond ’NOT stop’ is checked;

• If the condition expression is ’False’ (that is, the user has pressed Pause orGreenfoot.stop( ) has been called in the code), then the Run method ends.

• If the conditional expression is ’True’, then for each actor the act method is called.After the act method is executed for each actor, the method jumps back to thediamond and checks the conditional expression again. Is ’NOT stop’ still true?Then the ’True’ path is followed again and the act method is called again (loop).This continues to happen until the condition becomes ’False’. When the conditionis ’False’, then the method ends.

Note:In Greenfoot you can execute a method in several ways:

• By calling the method directly. Right-click on the object (for example, Mimi) andselect the method.

• Press the Act button. For this to work, the method must be called in thevoid act( ) code.

• Press the Run button. Here too, for this to work, the method must be called in thevoid act( ) code. In this case, the method is not called once, but continuously.That can be particularly useful if you want to see what multiple steps do. Forexample, taking many steps to reach an egg.

5.3.1 (IN) Understanding the while

Have a look at the flowchart in figure 10 above.

1. Which language construct (i.e. code control structure, such as if .. then .. else or while) isassociated with this flowchart?

2. What needs to happen before the ’False’ path can be followed?

3. Draw a new flowchart in which you swap ’NOT stop’ with ’stop’ and ’False’ with ’True’. Isthe flowchart still correct? Explain why not.

Greenfoot feature: while loop in the RunThe Run command is a built-in feature in Greenfoot and cannot be changed. Therefore, theRun flowchart with its while loop always remains the same. In a few previous exercises youdescribed algorithms which make use of a while to repeat certain steps. An example is the’find-the-egg’ algorithm which used: ”While not egg found, take a step.” Figure 11 showsthe corresponding flowchart. If you wish, you can look back at the flowchart and code thatyou wrote in assignment 2, part 5.3.1.

Algorithmic thinking and structured programming (in Greenfoot) 11

Page 12: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

Figure 11: Flowchart for ’find-the-egg’ algorithm (assignment 2, part 5.3.1)

If you press the Run button, then the act method will continuously be executed. That’s apart of Greenfoot. But in this case, after executing the act, the algorithm will be done. Thewhile loop in act is repeatedly called until the egg has been found. So, after one Act the eggwill have been found, and in each next act call nothing will happen. This makes the use ofthe Run (which repeatedly calls an Act) rather useless in this context.

Actually, using the Run is only useful if the algorithm consists of repeating the same stepsover and over again. The step that must be repeated must then be placed in the act method.So, instead of this flowchart:

it’s better to draw this flowchart:

Algorithmic thinking and structured programming (in Greenfoot) 12

Page 13: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

As you see, in this flowchart the while loop in Run always remains the same. From nowon we will therefore not draw the while loop anymore. You won’t find the loop anywhere inthe code either: it is built-in Greenfoot.

5.3.2 Find the egg using while (instead of if .. then .. else .. )

In assignment 2, part 5.3.1 you implemented the ’find-the-egg’ algorithm (a summary explanationof the algorithm and its corresponding flowchart is given in the theory block above).

1. In your own words, describe the goal of the algorithm.

2. Have a look at the void act( ) flowchart that you used for that exercise. If you can’t find it,then have a look at figure 11 in the theory block above.

3. Which language construct (i.e. code control structure) is associated with this flowchart?

4. Which agreement dit we now make about using a while in the act?

5. Change the flowchart for the ’find-the-egg’ algorithm so that it does not use a while.

6. We are now going to test if your flowchart without the while means the same. To do this wewill translate the new flowchart into code and check if the program does what we expect itto do. We’re going to modify the code:

(a) Replace the code in MyDodo’s act method by the code which originally belonged to theflowchart (with the while) to restore the code like it was in assignment 2. That was thefollowing code:

/*** Keep moving forward until you find the egg

*/public void act ( ) {

while( !foundEgg ( ) ){move ( ) ;

}}

(b) Compile, run, and test. We are now sure that the original code has been restored prop-erly.

(c) Now modify this code so that it corresponds to your new flowchart.

(d) Compile, run, and test.

Algorithmic thinking and structured programming (in Greenfoot) 13

Page 14: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

(e) Open the ’world Aanroepen6movesAlsWhile.txt’ world.

(f) Test your algorithm using the Run button. Does the program do what you expect?

(g) What can you say about the agreement that you described in part 4? Does that agree-ment change the outcome of the program?

7. Save your scenario so that you can hand it in at the end of the assignment.

(a) In Greenfoot choose ’Scenario’ from the main menu, and then ’Save As ...’.

(b) Choose a file name containing your own name and assignment number 3b, for exam-ple: Asgmt3b_John.

We have now seen that you can sometimes replace a while in an actmethod by an if .. then .. elsestatement. The Run command ensures the repetition by continuously executing the act method.

Run or Act?You maybe wondering ”Why on Earth did they add a Run button?”. There are several reasonsfor this:

• Some scenarios involve multiple actors, each with their own act method. For example:if you place two MyDodo instances in the world, then each will have their own act. Tryit out. What you usually want is that all these objects (more or less) do something at thesame time. You won’t be able to do that if you have the entire task in the act method,but you will if you break the task down into smaller steps.

• You might want the program to respond to user-input (mouse or keyboard). Using theRun functionality you’re not forced to do everything at once in the act. By placingeverything in the act, it may take a long time before the program responds to any user-input. Obviously that’s not the intention, and very frustrating for the user. By using theRun, your program can quickly respond to user-input.

Run if you canFrom now on we will try to set-up the program so that one step in the algorithm is placed inthe act method. Then, when the Run button is pressed, the entire program is executed. Formost programs, this is not an issue. It only gets tricky when you want actors to do somethingquite complex. In that case, we won’t use the Run or act, but rather implement our algorithmin one or more sub-methods and then call this by right-clicking on the object.

5.4 Finding the egg with several obstacles

We will now further investigate how the Run or act work. Have a look at the following world:

Algorithmic thinking and structured programming (in Greenfoot) 14

Page 15: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

Figure 12: Scenario for exercise 5.4

1. We will continue with the scenario which you saved previously in exercise 5.2.1 part 4 (forexample: Asgmt3a_yourName). Open that scenario.

2. Open the world: ’world egg2FenceInWay’.

(a) Right-click on an empty square in the world.

(b) Choose void populateFromFile( ).

(c) Navigate to the folder ’worlds’.

(d) Choose ’world egg2FenceInWay.txt’

3. (IN) Is your code generic enough to work properly in this world? Can you use it to helpMimi find her egg?

4. Test your code by pressing the Act button twice. Does Mimi walk around both fences? Ifshe doesn’t, modify your code appropriately.

5. Open the world ’world egg2FenceInWay’ again.

6. What happens now when you press Run?

7. (IN) In your own words describe why Mimi doesn’t stop after having found the egg. Tip: ifyou have problems with this, then read the explanation in chapter 5.3 again.

We have now seen that Act is repeatedly called by pressing on the Run button.

5.5 Giving compliments

StringIn Java, text is called a String. String is a type, just like int and boolean. A parametercan be a String. Thus a method call can also be given a String (or text) as a parameter. Ifyou want to use a particular text in your program, you need to use quotation marks (see thefollowing example). You can do all sorts of things with Strings, such as glue two together(called concatenate) using ’+’. As such, "Hello" + " Mimi" becomes "Hello Mimi".String example:The method showCompliment(String compliment) has a String parameter called ’compli-ment’. It makes a dialog window appear showing the text ’compliment’.

Figure 13: Result after calling:showCompliment( "Congratulations!");

When Mimi finds her egg, we want to give her a compliment. To do this, we will add code to theact( ) method in MyDodo.

1. As a starting point we take the flowchart that you made for the act in exercise 5.2.1. WhenMimi finds the egg, we compliment her on her job well-done. Add this to the flowchart infigure 14.

Algorithmic thinking and structured programming (in Greenfoot) 15

Page 16: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

Figure 14: Flowchart for act method in ”Walk around the fence” exercise (ex 5.2.1)

2. To show the compliment, you can use the method showCompliment( String compliment ).This makes a dialog window appear showing the compliment’s text.

3. Modify the act( ) method’s code so that a compliment is shown.

4. Don’t forget to change the comments above the act( ) method too.

5. Compile, run, and test the program. Does it work as expected?

6. Change the compliment’s text so that Mimi knows why you are congratulating her.

7. Compile and test the program again. Does it work as expected?

We have now seen how you can use a conditional expression to select different methods for ex-ecution: using the if .. then .. else statement, either the methods in the if branch or the methodsin the else branch will be called. We also saw how to display a dialog window with a particulartext.

5.6 Stopping the program

When you press the Run button you will see that Mimi doesn’t stop after she finds the egg. That’sbecause of Greenfoot’s built-in while loop in the Run. We saw this in exercise 5.3. We are nowgoing to modify the program so that it stops when Mimi finds her egg:

1. Open MyDodo’s code and find the act( ) method.

2. Add code to stop the program from running when the egg is found. Tip: use Greenfoot.stop( ); .

3. Compile and test the program using the Run button. Does it work as expected?

We have now seen how you can use Greenfoot.stop( ) to interrupt the Run and stop the pro-gram.

5.7 Testing a program in several worlds

In this assignment we’ve made quite some code modifications. It’s time to look back a momentand reflect on what we’ve done. What can Mimi do well now, and what does she still have tolearn?

Algorithmic thinking and structured programming (in Greenfoot) 16

Page 17: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

1. What is the goal of your program? Describe what it must do to work correctly. When areyou satisfied? What is the desired final situation?

2. Open the ’world egg3FenceInWayWithSpace’ world.

3. Test the program using Run.

4. Explain how it’s possible that Mimi finds her egg in this world too.

5. Is your code generic enough to work in the following world too?

Figure 15: Scenario with four fences

6. (IN) Briefly describe how generic your program is.

7. Drag Mimi, the fences, and the blue egg to different coordinates in the world. Test if theprogram works as expected. Try a few more positions.

8. (IN) For which initial situations does the program not work correctly?

9. (IN) Describe the initial situation in which the program works correctly.

10. (IN) Make at least two suggestions for improving your program (you don’t have to makethe improvements, only give suggestions).

11. (IN) What are the two most important things that you have learned during this assignment?

We have now seen that a generic program works in many different situations.

6 Summary

In this assignment you have been introduced to generic and elegant algorithms.

You can now:

• describe how the Act and the Run works;

• use combinaties of sequences, selections (choices), and repetitions in flowcharts and code;

• write sub-methods for repetitive tasks or to break down complex methods into manageabletasks;

• optimize flowcharts and code;

• modify code in a structured and incremental manner;

• describe the advantages of a generic solution;

• determine if a solution is correct.

Algorithmic thinking and structured programming (in Greenfoot) 17

Page 18: Assignment 3: Optimizing solutionssjakie/Greenfoot/Kandinsky/DodoAssignment3.pdf · Assignment 3: Optimizing solutions – Algorithmic Thinking and Structured Programming (in Greenfoot)

Optimizing solutions Assignment 3

7 Saving your work

You have just finished the third assignment. Save your work! You will need this for future as-signments. In the Greenfoot menu at the top of the screen, select ’Scenario’ and then ’Save’. Younow have all the scenario components in one folder. The folder has the name you chose whenyou selected ’Save As ...’.

8 Handing in

Hand the flowcharts on paper (those indicated with an ’(IN) ’) into the pigeon hole outside theteachers’ lounge, name: ’Renske Smetsers’. (You may also scan/photograph them and paste theminto your (Word) document.)

Hand your (digital) work in via email to [email protected]:

1. Go to the folder where you saved your work (for example: Asgmt3b_yourName).

2. With each scenario a ’README.TXT’ file is automatically generated. Open the ’README.TXT’file and type your name(s) at the top.

3. Do the same for the first scenario in this exercise (for example: Asgmt3a_yourName).

4. Place the (Word) document with your answers to be handed in (answers to the ’(IN) ’ ques-tions) in the same folder. Make sure your name(s) are in the document.

5. Compress the entire file into one .zip file. In Windows you can do this by right-clicking onthe folder and choosing ’Send to’ and then ’Compressed (zipped) folder’.

6. Hand the compressed (zipped) folder in via Magister.

Make sure you hand your work in before next Wednesday 8:30 (in the morning).

Algorithmic thinking and structured programming (in Greenfoot) 18