DCS/100: Procedural Programming

Similar documents
DCS/100: Procedural Programming

DCS/100: Procedural Programming

DCS/100 Procedural Programming

QUEEN MARY, UNIVERSITY OF LONDON

CONDITIONAL EXECUTION: PART 2

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

printf( Please enter another number: ); scanf( %d, &num2);

Intro. Scheme Basics. scm> 5 5. scm>

Midterms Save the Dates!

These are notes for the third lecture; if statements and loops.

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

If you don t, it will return the same thing as == But this may not be what you want... Several different kinds of equality to consider:

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

5. Control Statements

1007 Imperative Programming Part II

Introduction to Software Development (ISD) Week 3

SELECTION. (Chapter 2)

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

The compiler is spewing error messages.

In this lab, you will learn more about selection statements. You will get familiar to

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Java Programming: from the Beginning. Chapter 8 More Control Structures. CSc 2310: Principle of Programming g( (Java) Spring 2013

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

CS354 gdb Tutorial Written by Chris Feilbach

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

If Statements, For Loops, Functions

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

CS 251 Intermediate Programming Java Basics

Control Structures in Java if-else and switch

Boolean Expressions. Is Equal and Is Not Equal

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to:

Boolean Expressions. Is Equal and Is Not Equal

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Introduction to Programming Style

Computer Science II Lecture 1 Introduction and Background

Flow Control. CSC215 Lecture

CS112 Lecture: Making Choices

4. Java Project Design, Input Methods

QUIZ Friends class Y;

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

Week - 01 Lecture - 04 Downloading and installing Python

6.096 Introduction to C++

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

Lecture 19 CSE August You taught me Language, and my profit on t is I know how to curse. William Shakspere, The Tempest, I, ii.

CS 177 Recitation. Week 1 Intro to Java

Lecture 10: for, do, and switch

(Refer Slide Time: 1:27)

Chapter 6. More Complex Conditionals. 6.1 Nested Conditionals

CS 426 Fall Machine Problem 1. Machine Problem 1. CS 426 Compiler Construction Fall Semester 2017

COMP : Practical 8 ActionScript II: The If statement and Variables

c122mar413.notebook March 06, 2013

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Lecture 1: Overview

Text Input and Conditionals

C Pointers 2013 Author Riko H i

QUIZ: What value is stored in a after this

Key questions to ask before commissioning any web designer to build your website.

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Racket Style Guide Fall 2017

Notes on Non-Chronologic Backtracking, Implication Graphs, and Learning

Midterms Save the Dates!

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CS121: Computer Programming I

This Week s Agenda (Part A) CS121: Computer Programming I. Changing Between Loops. Things to do in-between Classes. Answer. Combining Statements

How To Get Your Word Document. Ready For Your Editor

Ex: If you use a program to record sales, you will want to remember data:

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

C++ Style Guide. 1.0 General. 2.0 Visual Layout. 3.0 Indentation and Whitespace

Lecture Transcript While and Do While Statements in C++

Part 2: The Material PART 2

CS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014

Understanding Recursion

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

(Refer Slide Time 3:31)

MATLAB TUTORIAL WORKSHEET

CS Programming I: Arrays

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

Variables and literals

Lecture 5 8/24/18. Writing larger programs. Comments. What are we going to cover today? Using Comments. Comments in Python. Writing larger programs

Introduction to Programming using C++

Starting to Program in C++ (Basics & I/O)

CS Summer 2013

Introduction to L A TEX for MCS-236

Controls Structure for Repetition

Chapter 6: The C Preprocessor

Announcements. CS18000: Problem Solving And Object-Oriented Programming

Case Control Structure. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

Transcription:

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