+ All Categories
Home > Documents > Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control...

Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control...

Date post: 26-Dec-2015
Category:
Upload: joshua-logan
View: 215 times
Download: 0 times
Share this document with a friend
Popular Tags:
25
Learning to Program with Learning to Program with C# - 7 C# - 7 1 Unit 7 Unit 7 Introduction to Control Flow Introduction to Control Flow concepts concepts Sequence Sequence Repetition Repetition Conditional Conditional Introduce values, minimally, at Introduce values, minimally, at the same time the same time See how these can be used to See how these can be used to automatically fly the rocket automatically fly the rocket
Transcript
Page 1: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

11

Unit 7Unit 7

• Introduction to Control Flow Introduction to Control Flow conceptsconcepts– SequenceSequence– RepetitionRepetition– ConditionalConditional

• Introduce values, minimally, at the Introduce values, minimally, at the same timesame time

• See how these can be used to See how these can be used to automatically fly the rocketautomatically fly the rocket

Page 2: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

22

Programs must Programs must dodo somethingsomething

• Concentrated so far on the structure of a Concentrated so far on the structure of a modelmodel– the components, the members of each the components, the members of each

componentcomponent– the way in which models evolvethe way in which models evolve– this is the unique part of the O-O modelthis is the unique part of the O-O model

• All programs, however, must All programs, however, must do do something in something in order to be effectiveorder to be effective– examine now the different ways of examine now the different ways of doingdoing– and how they can be expressed in prog languagesand how they can be expressed in prog languages

Page 3: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

33

We've looked at We've looked at doingdoing already…already…

• Remember playing with the Remember playing with the FlyFly method from the method from the RocketController?RocketController?– adjusting or creating a adjusting or creating a sequencesequence of of

operations/operations/statementsstatements

• A A statement statement is a single indivisible unit of doingis a single indivisible unit of doing• Execution model for a sequence of statements is Execution model for a sequence of statements is

simplesimple– they are executed, one at a time, from first to lastthey are executed, one at a time, from first to last

• Matches closely to some typical behaviours we Matches closely to some typical behaviours we see in everyday lifesee in everyday life– following a simple step by step cooking recipe, or our following a simple step by step cooking recipe, or our

work plan for the day – do this, then this, then thiswork plan for the day – do this, then this, then this

Page 4: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

44

Technical/Grammatical Technical/Grammatical details details

• A statement is always completed A statement is always completed with a semi-colonwith a semi-colon

• A sequence of statements can be A sequence of statements can be made to look like a single made to look like a single statement by…statement by…– enclosing it in bracesenclosing it in braces– this is used all the time, as we'll see this is used all the time, as we'll see

laterlater

Page 5: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

55

More advanced forms of More advanced forms of doing…doing…

• Is this sequencing of operations enough?Is this sequencing of operations enough?• No, not typically, becauseNo, not typically, because

– It is inflexibleIt is inflexible• no opportunity to adjust our behaviour according to what no opportunity to adjust our behaviour according to what

we find in our environmentwe find in our environment– for example, a simple daily working plan does not explicitly for example, a simple daily working plan does not explicitly

tell you what to do if there's a fire alarmtell you what to do if there's a fire alarm– remember the rocket – we needed to know the environment remember the rocket – we needed to know the environment

before setting outbefore setting out

– It is inefficientIt is inefficient• if we want to do something repeatedly, we must write the if we want to do something repeatedly, we must write the

repetitions out in fullrepetitions out in full

• So what do we need?So what do we need?

Page 6: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

66

ConditionalConditional doing doing– Certain doing is performed only if some condition is Certain doing is performed only if some condition is

metmet– Various ways we express this notion in EnglishVarious ways we express this notion in English

• "I'll take an umbrella if it's raining""I'll take an umbrella if it's raining"• "If it's raining then I'll take an umbrella""If it's raining then I'll take an umbrella"• "If it's raining or it's cloudy then I'll take an umbrella, "If it's raining or it's cloudy then I'll take an umbrella,

otherwise I'll take a sunhat"otherwise I'll take a sunhat"• "If it's raining then I'll take an umbrella, otherwise if it's very "If it's raining then I'll take an umbrella, otherwise if it's very

sunny then I'll take a sunhatsunny then I'll take a sunhat

– NoticeNotice• They all express doing, with some condition attachedThey all express doing, with some condition attached• Sometimes, nothing will be done at allSometimes, nothing will be done at all• Sometimes, we are choosing between alternatives – Sometimes, we are choosing between alternatives –

something will always be donesomething will always be done

Page 7: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

77

Stating this in a prog. Stating this in a prog. languagelanguage

• The statement forms most often found:The statement forms most often found:– "IF a condition holds THEN do something""IF a condition holds THEN do something"

• note, if the condition doesn't hold, nothing is donenote, if the condition doesn't hold, nothing is done

– "IF a condition holds THEN do something "IF a condition holds THEN do something ELSE do a different thing"ELSE do a different thing"• one or other of the two things must be doneone or other of the two things must be done• which one is decided when the condition is which one is decided when the condition is

evaluated – see the next slideevaluated – see the next slide

• There are othersThere are others– we'll leave them for nowwe'll leave them for now

Page 8: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

88

Notice the Notice the conditioncondition• "a condition holds""a condition holds" from previous slide from previous slide

– used in both forms – what does it mean?used in both forms – what does it mean?

• a condition is a factual statement to be verified as a condition is a factual statement to be verified as true or falsetrue or false– factual statementsfactual statements

• it is rainingit is raining• her hair is blackher hair is black• there is an obstacle aheadthere is an obstacle ahead

– a condition holdsa condition holds means that the statement was verified means that the statement was verified as being trueas being true

• When does the verification take place?When does the verification take place?• at the point when the decision must be madeat the point when the decision must be made• when the conditional statement is executedwhen the conditional statement is executed• crucially – not until the program is runningcrucially – not until the program is running

Page 9: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

99

Values, expressions and Values, expressions and evaluationevaluation

• To avoid confusion between To avoid confusion between doingdoing statements, and statements, and factualfactual statements statements– the latter are called the latter are called expressionsexpressions– they they expressexpress an idea or a computation… an idea or a computation…– ……which is which is evaluatedevaluated to produce a to produce a valuevalue

• In the case of a conditional expressionIn the case of a conditional expression– the idea evaluates to 'true' or 'false'the idea evaluates to 'true' or 'false'

• these are just two values in the great these are just two values in the great universe of values that we'll be exploringuniverse of values that we'll be exploring

Page 10: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

1010

Repetitive Repetitive doingdoing

• A statement of doing is repeated a A statement of doing is repeated a number of timesnumber of times– sometimes the number is known in sometimes the number is known in

advanceadvance– sometimes we only know when to stop at sometimes we only know when to stop at

some point in the middle of the repetitive some point in the middle of the repetitive activityactivity• in these cases, again, a condition is used to in these cases, again, a condition is used to

determine when to stop – perhaps continue determine when to stop – perhaps continue repeating the activity as long as the condition repeating the activity as long as the condition holds, stopping when it no longer holdsholds, stopping when it no longer holds

Page 11: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

1111

Consider these Consider these statements:statements:

– Fill the fridge with beerFill the fridge with beer• number of repeats known in advance: nonumber of repeats known in advance: no• repeated action: put another beer in fridgerepeated action: put another beer in fridge• condition: The fridge is not fullcondition: The fridge is not full

– Change the spark plugs in the carChange the spark plugs in the car• number of reps known in advance: yesnumber of reps known in advance: yes• repeated action: change the next plugrepeated action: change the next plug

– Do up shirt buttonsDo up shirt buttons• reps known in advance: usually not!reps known in advance: usually not!• repeated action: move hand to next button and do it uprepeated action: move hand to next button and do it up• condition: Some buttons unfastenedcondition: Some buttons unfastened

– Add up a series of numbersAdd up a series of numbers• reps known in advance: sometimes, sometimes notreps known in advance: sometimes, sometimes not• repeated action: get next number, add it to running totalrepeated action: get next number, add it to running total• condition: More numbers available in the seriescondition: More numbers available in the series

Page 12: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

1212

How are these expressed?How are these expressed?• We need a formal way of expressing these…We need a formal way of expressing these…

– whilewhile the fridge is not full the fridge is not full,,put another beer input another beer in

– forfor eacheach cylinder cylinder,,change spark plug in that cylinder for new onechange spark plug in that cylinder for new one

– whilewhile there are buttons undone there are buttons undone,,pick an undone one and fasten itpick an undone one and fasten it

– whilewhile there are more numbers in the list there are more numbers in the list,,read the next one and add it to the totalread the next one and add it to the total

• Notice the structuringNotice the structuring– while: the condition and the repeated activitywhile: the condition and the repeated activity– for: the number of reps is implicitly specifiedfor: the number of reps is implicitly specified

Page 13: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

1313

Step up in Step up in understanding…understanding…

• The flat textual description comes to life The flat textual description comes to life only when it is executedonly when it is executed– you need to be able to imagine this happeningyou need to be able to imagine this happening– the concept seems easy, but the reality is often the concept seems easy, but the reality is often

harder to absorbharder to absorb

• For example,For example,whilewhile the fridge is not full the fridge is not full,,

put another beer input another beer in– might result in 100 executions of "put another might result in 100 executions of "put another

beer in" – we don't know from simply looking at beer in" – we don't know from simply looking at the textthe text

• The conditionals similarlyThe conditionals similarly– we don't know precisely what will happen until we don't know precisely what will happen until

they are executedthey are executed

Page 14: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

1414

Conditional statements in Conditional statements in C#C#

• Single option conditional statementSingle option conditional statement– (do nothing if condition doesn't hold)(do nothing if condition doesn't hold)

– This is a template. The words in italics are expanded out in use This is a template. The words in italics are expanded out in use to be a valid expression and statement. Remember that a to be a valid expression and statement. Remember that a sequence of statements can be viewed as one statement with sequence of statements can be viewed as one statement with bracesbraces

• Conditional with two alternativesConditional with two alternatives– The condition decides which of two actions to performThe condition decides which of two actions to perform

• To execute these statementsTo execute these statements– condition is evaluated first. The appropriate statement is then condition is evaluated first. The appropriate statement is then

executed, if any, depending on the resultexecuted, if any, depending on the resultif( Condition ) Statement else Statement

if( Condition ) Statement

Page 15: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

1515

Repetitive Statements in Repetitive Statements in C#C#

• We will look at just one for nowWe will look at just one for now– typically used when we don't know in advance how typically used when we don't know in advance how

many repetitions requiredmany repetitions required

– To execute this statementTo execute this statement• first the condition is evaluatedfirst the condition is evaluated• if it is true thenif it is true then

– the contained statement is executedthe contained statement is executed– we start executing the whole we start executing the whole whilewhile statement from the top statement from the top

againagain• elseelse

– the condition is false and we complete execution of the whole the condition is false and we complete execution of the whole while while statement. The contained statement is NOT executedstatement. The contained statement is NOT executed

while( Condition ) Statement

Page 16: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

1616

See it in action - See it in action - AdvancedRocketryAdvancedRocketry

• Run ExecuteMission againRun ExecuteMission again– this should be using AutoRocketControllerthis should be using AutoRocketController– when the when the landing sequence engagedlanding sequence engaged message message

comes up, the comes up, the LandLand method is executing method is executing

• Before examining that method closelyBefore examining that method closely– how would you try to land the rocket safely?how would you try to land the rocket safely?– in this rocket version, in this rocket version, safelysafely means means

• upright, nose pointing upwardsupright, nose pointing upwards• but could be travelling at any speed down or but could be travelling at any speed down or

sidewayssideways• (it's a sturdy rocket, this one!)(it's a sturdy rocket, this one!)

Page 17: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

1717

Getting to the ground – Getting to the ground – how?how?• RequirementsRequirements

– Must be uprightMust be upright– Must be dropping downwardsMust be dropping downwards– Must stop once we've reached the groundMust stop once we've reached the ground– Speed sideways or downwards unimportantSpeed sideways or downwards unimportant

• So…?So…?– To be dropping downwards but uprightTo be dropping downwards but upright

• Engines must be turned off, let gravity do the workEngines must be turned off, let gravity do the work

– As we coast downwards, must check periodically to see whether As we coast downwards, must check periodically to see whether we've reached the groundwe've reached the ground

• Procedure:Procedure:– Turn engines offTurn engines off– Get uprightGet upright– Get to groundGet to ground

Page 18: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

1818

– Examine the Land methodExamine the Land method• Engines off is easy enough – simply a method Engines off is easy enough – simply a method

callcall• Getting upright is trickierGetting upright is trickier

– Don't know the starting attitudeDon't know the starting attitude– Hence continually test to see if the rocket is tiltingHence continually test to see if the rocket is tilting

» if it is, then nudge it round by 1 degreeif it is, then nudge it round by 1 degree» eventually, after enough repeats, the rocket will be eventually, after enough repeats, the rocket will be

uprightupright– Note that Note that IsTiltingIsTilting returns a true or false value returns a true or false value

» known as a Boolean, or known as a Boolean, or boolbool for short for short

ARocket.EnginesOff();

// Get upright againwhile( ARocket.IsTilting() ){

ARocket.TurnLeft( 1 );}

… there's more…

Page 19: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

1919

– Finally, to get to the groundFinally, to get to the ground• Must ask the Arena how close we are to the groundMust ask the Arena how close we are to the ground• while we are still above it, we must continue to Coast while we are still above it, we must continue to Coast

with engines off – hence fall downwardswith engines off – hence fall downwards• How do we ask the Arena about positioningHow do we ask the Arena about positioning

– NearestBelowNearestBelow method returns distance to the nearest method returns distance to the nearest object below the supplied position. This distance is a object below the supplied position. This distance is a numbernumber

– We supply the position of the rocket, using GetPositionWe supply the position of the rocket, using GetPosition– The distance returned by The distance returned by NearestBelowNearestBelow is then tested to is then tested to

see if it is greater than zero (ie we're above the groundsee if it is greater than zero (ie we're above the ground– This final test gives us the true/false boolean value we This final test gives us the true/false boolean value we

need for the while statementneed for the while statement

// Get down to the ground// The condition in the while loop tests if we're above groundwhile( AArena.NearestBelow( ARocket.GetPosition() ) > 0 ){

ARocket.Coast( 1 );}

Page 20: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

2020

Try a Try a delicate delicate rocket…rocket…

• This rocket didn't care about landing This rocket didn't care about landing speed.speed.– In ExecuteMission, at the bottom, changeIn ExecuteMission, at the bottom, change

new AdvancedRocketnew AdvancedRocket

– totonew DelicateAdvRocketnew DelicateAdvRocket

• Rerun it to see what happensRerun it to see what happens– this rocket crashes if landing speed this rocket crashes if landing speed

downwards is greater than 20 and sideways downwards is greater than 20 and sideways motion is greater than 10motion is greater than 10

Page 21: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

2121

See if you can do better…See if you can do better…• Go to Go to SmartLander.csSmartLander.cs

– a derived class of AutoRocketControllera derived class of AutoRocketController– overriding ONLY the overriding ONLY the LandLand method method– initially it is the same as AutoRocketControllerinitially it is the same as AutoRocketController– Adjust ExecuteMission, so it uses this controller Adjust ExecuteMission, so it uses this controller

instead of AutoRocketControllerinstead of AutoRocketController• change needed at bottom of filechange needed at bottom of file

• See if you can work out how to slow the rocket See if you can work out how to slow the rocket gently so it doesn't crash hardgently so it doesn't crash hard

• Take the following hints one at a time, working to Take the following hints one at a time, working to get an answer on each before going to the nextget an answer on each before going to the next

Page 22: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

2222

HintsHints

– You can brake the descentYou can brake the descent• by firing the engines for a short timeby firing the engines for a short time

– Do you always need to brake the descent?Do you always need to brake the descent?– If not alwaysIf not always

• what is the condition for firing the rocket?what is the condition for firing the rocket?

– There is a testing method FallingFasterThanThere is a testing method FallingFasterThan• you pass a number – it returns true if the rocket is you pass a number – it returns true if the rocket is

falling faster than this valuefalling faster than this value

– The answer is on the next slideThe answer is on the next slide• only go on if you are totally stuckonly go on if you are totally stuck• just try something outjust try something out

Page 23: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

2323

General planGeneral plan

• Inside the repetitive loop taking the Inside the repetitive loop taking the rocket to the groundrocket to the ground– you need to check how fast the rocket is you need to check how fast the rocket is

falling, if it's too fast, fire the rocketsfalling, if it's too fast, fire the rockets– sounds like a conditional statementsounds like a conditional statement

• what is the condition?what is the condition?• what is the actionwhat is the action

– if the condition is true?if the condition is true?– if the condition is false?if the condition is false?

– code on next slide…code on next slide…

Page 24: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

2424

• Try this out, if you didn't get thereTry this out, if you didn't get there• Try also now to slow the sideways motionTry also now to slow the sideways motion

– methods available to test speed sidewaysmethods available to test speed sideways– similar technique should be usedsimilar technique should be used– when will you do the sideways braking?when will you do the sideways braking?

» I suggest I suggest beforebefore this while statement, and after you've got the rocket this while statement, and after you've got the rocket back uprightback upright

– if you need it, there's some useful code in if you need it, there's some useful code in spare code.txtspare code.txt

// Get down to the groundwhile( AArena.NearestBelow( ARocket.GetPosition() ) > 0 ){

if( ARocket.FallingFasterThan( 20 ) ){

ARocket.IncThrustLevel( 10 ); // Turn engines on toARocket.Coast( 1 ); // brake the fallARocket.EnginesOff();

}else {

ARocket.Coast( 1 ); // fall with no brakes}

}

Page 25: Learning to Program with C# - 71 Unit 7 Introduction to Control Flow conceptsIntroduction to Control Flow concepts –Sequence –Repetition –Conditional Introduce.

Learning to Program with C# Learning to Program with C# - 7- 7

2525

SummarySummary

• Explored the structure inside methods, Explored the structure inside methods, the code that does somethingthe code that does something– the statementthe statement– sequences of statementssequences of statements– conditional statements - ifconditional statements - if– repetitive statements - whilerepetitive statements - while

• Necessarily looked atNecessarily looked at– expressions, values and evaluationexpressions, values and evaluation

• We'll explore these more in the next We'll explore these more in the next unitunit


Recommended