DCS/100: wk 3 p.1/50 DCS/100: Procedural Programming Week 3: Making Decisions Queen Mary, University of London
DCS/100: wk 3 p.2/50 Last Week From last week you should be able to explain and write programs that use the following: variables types initialization and assignement expressions
DCS/100: wk 3 p.3/50 This Week At the end of this week you should be able to: write programs that make decisions explain the use of boolean expressions explain what is meant by if and switch statements trace programs containing if and switch statements
DCS/100: wk 3 p.4/50 Decisions, Decisions Straightline programming isn t enough. You have to be able to do different things in different circumstances. Example: Q: Which courses should I take this semester? A: if you are a G400 student, then Programming, Logic, Computer Architecture and C&S, but if you are a G4N1 student, then Programming, Logic, Computer Architecture and..., and if you are a...
DCS/100: wk 3 p.5/50 Cases Or imagine a cash machine: Do you want cash or a statement?...or your mobile phone with all those menus of options.
DCS/100: wk 3 p.6/50 If statements Programming languages solve this by having if statements: char ans= n ; out.write("hi, would you like me "); out.write("to insult you? "); ans = in.read(); if (ans == y ) out.writeln("you big ugly baboon!"); else out.writeln("oh, all right then.");
DCS/100: wk 3 p.7/50 if statement Form: if (<test>) <statement> else <statement>
DCS/100: wk 3 p.8/50 Flow of control is ans== y? yes no print insult don t print insult
DCS/100: wk 3 p.9/50 Doing more than one thing But often you want to do more than one thing: if (ans == y ) { out.writeln("you big ugly baboon!"); } else { out.writeln("oh, all right then."); out.writeln("i won t."); } Instead of a single command, you can put a whole sequence inside braces: {... }
DCS/100: wk 3 p.10/50 Doing more than one test You can do a sequence of tests: if (ans == y ) out.writeln("you big..."); else if (ans == n ) out.writeln("ok, I won t."); else out.writeln("answer yes or no!"); You can easily build these up to the point where your code is very opaque. Don t.
DCS/100: wk 3 p.11/50 The Infamous Dangling Else What does this mean? if (test1) if (test2) A; else B;
DCS/100: wk 3 p.12/50 The Infamous Dangling Else Is it if (test1){ { if (test2) A; } else B;
DCS/100: wk 3 p.12/50 The Infamous Dangling Else Is it or is it if (test1){ if (test1) { if (test2) { if (test2) A; A; } else else B; B; }
DCS/100: wk 3 p.12/50 The Infamous Dangling Else Is it or is it if (test1){ if (test1) { if (test2) { if (test2) A; A; } else else B; B; } There isn t a right answer. Some languages pick one and some the other. It doesn t matter which Java picks, Your code will be confusing if you depend on it.
DCS/100: wk 3 p.12/50 The Infamous Dangling Else Is it or is it if (test1){ if (test1) { if (test2) { if (test2) A; A; } else else B; B; } There isn t a right answer. Some languages pick one and some the other. It doesn t matter which Java picks, Your code will be confusing if you depend on it.
DCS/100: wk 3 p.13/50 Booleans The test you put in an if statement has to be something like: ans == y X <= 34 X*Y > 0 mystring.equals("dog") It is a yes/no question. It has to evaluate to either true or false. It has to be a Boolean expression.
DCS/100: wk 3 p.14/50 The Type: boolean We have a type: boolean for true or false things! It has two elements: true and false It is just like the other types (int, char, double, String). There are functions that return boolean. You can have boolean variables.
DCS/100: wk 3 p.15/50 Example boolean t = x==2; if (t) A; else B; is equivalent to if (x==2) A; else B; (This trick can make code with complicated tests much simpler to understand).
DCS/100: wk 3 p.16/50 Constructing booleans standard comparison operators: equal: ==, not equal:!=, less than: <, greater than: >, less than or equal: <=, greater than or equal: >= (cf. Brinch Hansen p35)
DCS/100: wk 3 p.17/50 Beware: = and == USE == (comparison) DON T USE = (assignment) Read = as gets the value of NOT equals.
DCS/100: wk 3 p.18/50 Constructing booleans combinations through boolean operators (called connectives): and: & or && or: or not:! (cf. Brinch Hansen p37 and Logic and Proof course) Examples: ans== y ans == Y X>0 & Y>0
DCS/100: wk 3 p.19/50 Equals for strings Java has two types of objects, simple and complicated (they re not technically called that). == and its ilk only work for simple objects. For complicated objects they only tell you whether the objects are represented internally in Java by the same bit of memory. Strings are complicated. This means: USE DON T USE mystring.equals( Hello World! ) mystring == Hello World!
DCS/100: wk 3 p.20/50 Blocks Java (and many other languages) have two sorts of statements: Simple statements: have to be ended by a semi-colon x = x+1; ans = in.readline(); Compound statements: (or blocks) sequences of statements enclosed in braces. { A; B; C; D;} A block is a statement, and can be used anywhere a statement is expected. NOTE: variables can only be used inside the blocks in which they are declared.
DCS/100: wk 3 p.21/50 Tracing If statements Trace using a series of boxes showing the values of variables, the following code for values input of 3, 10 and 11. You may also wish to use extra question boxes for boolean expressions. int price = 0; int weight = in.readint(); if (weight <= 5) price = 2; else if (weight <= 10) price = 4; else price = 6; out.writeln("the cost is " + price);
DCS/100: wk 3 p.22/50 ParcelForce 9am ParcelForce use a table to determine the cost of parcels. Prices are computed (for 9am deliveries) as follows: 10kg or less: 30.35 more than 10kg: 30.35 plus 1.15 for each additional kg (or part kg) more than 30kg: not carried (The other times are all similar)
DCS/100: wk 3 p.23/50 ParcelForce 9am, cont Start by simplifying the problem forget about pounds and pence for the moment, just work in pence. The price structure is now: 10kg or less: 3035p more than 10kg: more than 30kg: 3035p plus 115p for each additional kg not carried
DCS/100: wk 3 p.24/50 Exercise Assume the weight of a new parcel in kg is in a variable weight. Write an if statement that puts the price into a variable price.
DCS/100: wk 3 p.25/50 ParcelForce 9am cont. So your problems are: how do I get the program to take a weight in grammes, and round it up to the nearest kilo? (week3 ex8) how do I get the program to print out a price in pence as a price in pounds and pence? (week3 ex7) By putting these three exercises together you get a program that works for the ParcelForce 9am service.
DCS/100: wk 3 p.26/50 Ex 8: if (cm%100 == 0) metres = cm/100; else metres = cm/100 + 1; (You have to convert this so it deals with grammes and kilos) Ex 7: pounds = cost/100; pence = cost%100; if (pence < 10) out.write("0"+pence); else out.write(pence);
DCS/100: wk 3 p.27/50 Boolean variables For example: boolean leap_year = (year%4==0 & year%100!=0) year%400==0; if (leap_year)... else...
DCS/100: wk 3 p.28/50 Systematic testing Read Brinch Hansen ch3 pp51-55. You re writing programs whose behaviour is more complicated now. Systematic testing is very important. In industry more effort goes into testing code than writing it. It is impossible to test programs exhaustively (every possible input), so representative cases have to be picked.
DCS/100: wk 3 p.29/50 Systematic testing The idea is to test each possible program behaviour, not each possible input. For complex program behaviours there are still lots of cases, and the testing has to be done on an automated test-bed. Complex programs have to be broken down into bits, and each bit tested separately. Microsoft employs more people to test code, than to write it. You have to take testing seriously too.
DCS/100: wk 3 p.30/50 Programming style and layout The point of having a high-level language is that it can be read and understood by people. This point is lost if the code is written down in a way that is hard for people to understand. Most industrial coding is maintenance. This means you will have to read, understand and change code written by other people. Worse: This means you will have to read, understand and change code written by yourself! You will need all the help you can get!
DCS/100: wk 3 p.31/50 Programming style and layout, cont There are some simple rules you can follow to make your program more easily readable. Brinch Hansen pp58-61 Jon Rowson s guidelines available on the web from the Course materials page
DCS/100: wk 3 p.32/50 Programming style and layout, cont These boil down to: choose informative names for variables (and later other things ) use layout to make the grammatical structure of the program clear
DCS/100: wk 3 p.33/50 The switch statement If you have a lot of cases to check it can look ugly to have a lengthy if statement (and can be slightly inefficient): Example: numbers for months int month; String name ="";... if (month == 1) name ="January"; else if (month == 2) name ="February"; else if (month == 3) name ="March"; else if (month == 4) name ="April";... else if (month == 11) name ="November"; else if (month == 12) name ="December"; else name ="not a month";
DCS/100: wk 3 p.34/50 Switch Many languages provide switch or case statements for this kind of thing. In Java they look like: int month; String name ="";... switch (month){ case 1: name ="January"; break; case 2: name ="February"; break; case 3: name ="March"; break; case 4: name ="April"; break;... case 11: name ="November"; break; case 12: name ="December"; break; default: name ="not a month"; break; }
DCS/100: wk 3 p.35/50 Switch NOTE THE break; STATEMENTS!
DCS/100: wk 3 p.36/50 Switch statements The general form is: switch (<expression>) { case <value1>: <statements> break; case <value2>: <statements> break;... case <valuen>: <statements> break; default: <statements> break; }
DCS/100: wk 3 p.37/50 Switch statements, cont You can give the cases in any order... (at least if they all have break s) default covers anything not mentioned in the other cases. You don t have to have it, and it does not have to come last. That s just good style.
DCS/100: wk 3 p.38/50 switch and if You don t really need switch if you have if: switch (<expression>) { case <value1>: <statements> break; case <value2>: <statements> break; default: <statements> break; } is the same as if (<expression> == <value1>) {<statements>} else if (<expression> == <value2>) {<statements>} else {<statements>}
DCS/100: wk 3 p.39/50 switch and if You don t really need if if you have switch: if (test) A; else B; is the same as switch (test) { case true: A; case false: B; } or it would be, were it not for the fact that...
DCS/100: wk 3 p.40/50 In Java you can only switch on int and char As it says, you can t switch on booleans: switch (test) { case true: A; case false: B; } will not compile because test is a boolean, not an int or a char.
DCS/100: wk 3 p.41/50 In Java you can t... In other languages you can switch on booleans, and the equivalence holds. Similarly you cannot switch on Strings (cf wk3 ex5 planets).
DCS/100: wk 3 p.42/50 What does break do? If you don t put in the break s, you can sometimes get very strange behaviour.
DCS/100: wk 3 p.43/50 What does break do? break means stop doing the switch and go on with the rest of the program. Without break you could execute several cases. But only if you change the value of the expression you re switching on during the switch! (You aren t allowed duplicate cases) (Do some Experiments... )
DCS/100: wk 3 p.44/50 Switch statements (Java tutorial): Following is an example,..., which illustrates why it might be useful to have case statements fall through:
switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numdays = 31; break; case 4: case 6: case 9: case 11: numdays = 30; break; case 2: if ( ((year % 4 == 0) &&!(year % 100 == 0)) (year % 400 == 0) ) numdays = 29; else numdays = 28; break; } DCS/100: wk 3 p.45/50
DCS/100: wk 3 p.46/50 Switch statements Compare this with the alternative: if the language did not fall through, but allowed multiple case and ranges instead...
switch (month) { case 1,3,5,7,8,10,12: numdays = 31; case 4,6,9,11: numdays = 30; case 2: if ( ((year % 4 == 0) &&!(year % 100 == 0)) (year % 400 == 0) ) numdays = 29; else numdays = 28; } DCS/100: wk 3 p.47/50
DCS/100: wk 3 p.48/50 Random Numbers Brinch Hansen s random number generator random gen = new random(1,365); creates a random number generator, called gen, that generates a stream of random numbers between 1 and 365. gen.readint() gives you the next number in the stream.
DCS/100: wk 3 p.49/50 Random Numbers, cont. The numbers aren t really random of course (they have to be generated by some deterministic algorithm, so give enough information you should be able to predict the next one). They are what s called pseudo-random, and that will be good enough for us.
DCS/100: wk 3 p.50/50 By the end of the week Once you have done the reading and the exercises you should be able to: Reading write programs that make decisions explain the use of boolean expressions explain what is meant by if and switch statements trace programs containing if and switch statements Brinch Hansen ch3 Computing Without Computers ch5 Jon Rowson notes on programming style