COMP101: Introduction to Programming in JAVA. Reading: Morelli Chapter 0, Chapter 2, Chapter 3, Cohoon and Davidson Chapter 1. For pseudocode see

Size: px
Start display at page:

Download "COMP101: Introduction to Programming in JAVA. Reading: Morelli Chapter 0, Chapter 2, Chapter 3, Cohoon and Davidson Chapter 1. For pseudocode see"

Transcription

1 Lecture 10 Algorithm Design COMP101: Introduction to Programming in JAVA Reading: Morelli Chapter 0, Chapter 2, Chapter 3, Cohoon and Davidson Chapter 1. For pseudocode see users.csc.calpoly.edu/ jdalbey/swe/pdl_std.html Russell Martin with some materials from Clare Dixon, Michele Zito, and Frans Coenen Department of Computer Science Russell.Martin(at)liv.ac.uk www2.csc.liv.ac.uk/ martin/teaching/comp101 Russell Martin Algorithm Design 1 / 81

2 Introduction We are describing a process that should be used when solving a given programming problem in Java. First, we talked about problem decomposition into classes and their attributes and representing these using class diagrams. Several questions are still unanswered: How do we find out what computation is needed to solve a particular problem? How do we describe such computation? How do we translate such descriptions into working Java code? Russell Martin Algorithm Design 2 / 81

3 Describing Computations The underlying assumption in our approach is that any computation (in fact almost any process you can think of) can be described by a sequence of steps each being, in turn, a (simpler) computation. Thus, processes like: Go to the local shop to buy milk Prepare spaghetti carbonara Search through a list of items to find a particular one Write a book Create the best video-game ever Write a Java program can all be described in terms of a sequence of steps that need to be completed to achieve the particular goal. Russell Martin Algorithm Design 3 / 81

4 Pseudocode standards The pseudocode language is a kind of structured English for describing processes. It allows the designer to focus on the logic of the process without being distracted by details of language syntax. A pseudocode description needs to be complete: it should describe the entire logic of the particular process so that implementation becomes a mechanical task of translating line by line into source code. The vocabulary used should be that of the problem domain, not of Java. The pseudocode is a narrative for someone who knows the requirements (problem domain), and is trying to learn how the solution is organised. Russell Martin Algorithm Design 4 / 81

5 Pseudocode conventions Each textbook and each individual designer may have their own personal style of pseudocode. There is no universal standard. Remember it is intended to be read by humans not computers. The format below inspired by jdalbey/swe/pdl_std.html is recommended for COMP101. Russell Martin Algorithm Design 5 / 81

6 Pseudocode conventions There are three main ways of doing things: sequence a process described as a sequence of steps occurring one after the other. I do this, then that, then that. selection a process described in terms of alternatives. If this happens, then I do this otherwise I do that. iteration a process described in terms of repeated executions of particular actions, sometimes subject to a termination condition. While there is still a coin in my purse, I pick one, remove it from the purse and add its value to a running total. We will look at pseudocode for selection and iteration in later weeks when we cover these issues in Java. Russell Martin Algorithm Design 6 / 81

7 Sequence A sequential process is indicated by writing one action after another, each action on a line by itself, and all actions aligned with the same indentation. The actions are performed in the sequence (top to bottom) that they are written. Example (non-computer) Example Brush teeth Wash face Comb hair Smile in mirror READ height of rectangle READ width of rectangle COMPUTE area as height multiplied by width Russell Martin Algorithm Design 7 / 81

8 Common Action Keywords Several keywords are often used to indicate common input, output, and processing operations. Input: READ, OBTAIN, GET Output: PRINT, DISPLAY, SHOW Compute: COMPUTE, CALCULATE, DETERMINE Initialize: SET Add one: INCREMENT Russell Martin Algorithm Design 8 / 81

9 Object Interactions Method invocation and message exchanging are achieved by specifying, in plain English, the name of the object that is called into action, the service (method, operation, functionality) asked from the named object, and the data needed to carry out the particular task. Examples. The Swimming Pool object mypool computes the volume of the pool. [The current object is to] Generate an instance of the Swimming Pool of length 5, width 4 and depth 2. Debit the Client account with ChequeAmount. Russell Martin Algorithm Design 9 / 81

10 Method definition Methods are defined by specifying their name, their input data, and the type of result they produce. Example. Carrying on from one of the examples on the previous slide, one may define METHOD Debit Account INPUT ChequeAmount : double OUTPUT None... <pseudocode describing the processing>... Russell Martin Algorithm Design 10 / 81

11 Golden Rules The main purpose of using pseudocode is to describe the system processing at an abstract level. (!) Rule 1 As mentioned before, one should avoid language specific constructs. The description should be in the language of the problem domain. Rule 2 If a pseudocode description is about the same length as the corresponding actual code it is probably too long! A pseudocode description for a method involving essentially a single Java statement is NOT NEEDED! Carefully chosen names for the method and its parameter list give enough information about its purpose. Russell Martin Algorithm Design 11 / 81

12 Approaches How do we find out what computation is needed to solve a particular programming task? For relatively simple programming tasks (similar to those that we will consider), one possible approach is to perform a two-level step-wise refinement process: 1 Decompose the task at hand in a number (usually much less than ten) of sub-tasks. 2 Reduce the sub-tasks to Java instructions. For complex tasks (these are not the type of problems we will consider in this module), usually people apply patterns. A number of computational problems have been studied in the literature. Given a new programming task, it is often possible to reduce it to a combination of well-known tasks that are then solved by applying standard well-known techniques. Russell Martin Algorithm Design 12 / 81

13 Examples: Computing timetofill() Problem Write a program to input the length, width and depth of a rectangular swimming pool of uniform depth and calculate the time it takes to fill it. Assume the rate of flow of water into the pool is 50 litres per minute and that 1 cubic metre has a capacity of 1,000 litres of water. SwimmingPoolUser + main(string[]) SwimmingPool - RATEOFFLOW: double = UNITCAPACITY: double = length: double - width: double - depth: double +timetofill(): double Russell Martin Algorithm Design 13 / 81

14 Initial Analysis From our verb analysis, we decided we needed the calculation of the time it takes to fill the pool. This will be a number, resulting from some calculations. We need to: 1 decide who is going to have responsibility of computing this; 2 think about its input data, return value and their types; 3 define a method that will perform such computation (let s call it timetofill). Russell Martin Algorithm Design 14 / 81

15 Responsibilities The responsibility for computing this could be either given to the SwimmingPoolUser class, in which case the method needs to get the values for length, width, and depth from somewhere else as the attributes in the SwimmingPool class are private to that class. Alternatively, the operation could be assigned to the SwimmingPool class, in which case the pool sizes would be available to the operation and no additional input data is needed. This looks like part of the behaviour of SwimmingPool so we will put it there. Thus if SwimmingPool is re-used in other programs, all the relevant methods will be provided. Russell Martin Algorithm Design 15 / 81

16 Scenarios 1 If the swimming pool contained 1 cubic metre of water its capacity would be 1,000 litres (this is in the problem statement!). If it takes a minute to pour 50 litres of water in the pool it would take 1, = 20 minutes to fill such a pool. 2 By a similar argument, if the swimming pool contained 5 cubic metres of water it would take 5 1, = 100 minutes to fill it. 3 Generalising, if the swimming pool contained x cubic metres of water this number should be multiplied by the unit capacity and divided by the rate of flow to give the correct answer. Thus, we get the answer (in minutes) from the Java expression: x * UNITCAPACITY / RATEOFFLOW Russell Martin Algorithm Design 16 / 81

17 Technical Issue Conceptually, X is the volume of the pool. Since the problem statement talks of a rectangular swimming pool of uniform depth, we see that x is the volume of a cuboid. Instead of x lets use poolvolume poolvolume = length * width * depth We assume that input lengths are in metres. Russell Martin Algorithm Design 17 / 81

18 Pseudocode for timetofill() As length, width and depth are all doubles, given the calculation involved, we probably want timetofill also to output a double. Here s the full specification of the required method: METHOD timetofill INPUT OUTPUT double COMPUTE the volume of the pool poolvolume as length x width x depth RETURN (poolvolume x UNITCAPACITY) / RATEOFFLOW Remark. It is arguable whether the given pseudocode is actually needed. In effect timetofill is formed by a single line of code. A pseudocode description is a bit of an overkill. (It was given here for pedagogical reasons.) Russell Martin Algorithm Design 18 / 81

19 The main method Assuming SwimmingPool gets the responsibility of running the method timetofill, the pseudocode for the main method is as follows. METHOD main INPUT args OUTPUT LOCAL DATA lth, wth and dth (all real numbers) READ lth, wth and dth from the keyboard SET up an instance mypool of Swimming Pool setting length=lth, width=wth and depth=dth PRINT the result of calling timetofill() on mypool. Russell Martin Algorithm Design 19 / 81

20 Another Example: Average Fuel Consumption Problem Write a program to input the cost of fuel put in the car each day of the (working) week, then compute the total cost and the average cost, and display the results of the two computations. FuelCostUser + main(string[]) FuelCost - moncost: double - tuescost: double - wedcost: double - thurscost: double - fricost: double +totalcost(): double +averagecost(): double Russell Martin Algorithm Design 20 / 81

21 Behaviours Write a program to input the cost of fuel put in the car each day of the (working) week, then compute the total cost and the average cost, and display the results of the two computations. We decided that we needed two methods totalcost and averagecost. Where are these located? For similar reasons as with timetofill() we will put them in the FuelCost class. What is their return type? Probably double as we need to perform calculations on values that are doubles. What pseudocode is needed for these methods? What pseudocode is needed for the main method? Russell Martin Algorithm Design 21 / 81

22 Summary We have shown how to use pseudocode to write down the behaviour of parts of the program. We have applied this to examples. Russell Martin Algorithm Design 24 / 81

23 Lecture 11 More About Methods COMP101: Introduction to Programming in JAVA Reading: Morelli Chapter 3, Cohoon and Davidson Chapters 2 and 4 Russell Martin with some materials from Clare Dixon, Michele Zito, and Frans Coenen Department of Computer Science Russell.Martin(at)liv.ac.uk www2.csc.liv.ac.uk/ martin/teaching/comp101 Russell Martin More About Methods 25 / 81

24 Overview In this lecture we have a closer look at methods. We look at the flow of control when using methods and how to pass information to the methods. We also discuss the scope and lifetime of identifiers. We give the implementation of the timetofill() method from the SwimmingPool class. Russell Martin More About Methods 26 / 81

25 Methods One of the core features of the objects in an object-oriented system is that they should be able to do things. Methods specify the things that objects in a given class can do. A method is a group of self-contained declarations and executable statements that performs a specific task or operation. As we have already seen, Java methods have the following format: Modifiers ReturnType Name (ParamList) { StatementList } Russell Martin More About Methods 27 / 81

26 Methods: Example The following was a method in the Rectangle class to calculate the area of the rectangle. // Method that returns the area of the rectangle. public int calculatearea() { return length * width; } We could add a method to the Rectangle class that prints out the rectangle s length and width. // Print out rectangle s length and width public void printdimensions() { System.out.println("Length: " + getlength() + " Width: " + getwidth()); System.out.println(); } Russell Martin More About Methods 28 / 81

27 Methods Control Flow // program to demonstrate how to call a // programmer-defined method public class TestMethodsControlFlow { } public static void main(string [] args) { System.out.println("Execution starts in [main] method;"); display(); System.out.println("back to the [main] method."); } // method to display a message public static void display() { System.out.println(" method [display] is then called;"); } >>>How does it work?<<< Russell Martin More About Methods 29 / 81

28 Running it! The first statement in the main method will print the message starting Execution starts... to the screen. Then Java executes display(). It does so by jumping inside the body of the method display at the bottom of the listing and running the method s single statement. The sentence method [display] is then called; appears on the screen. Then execution of the method ends, and the next statement that is executed is the one immediately following the call to display. The final line back to the [main] method. will appear on the screen. $ java TestMethodsControlFlow Execution starts in [main] method; method [display] is then called; back to the [main] method. $ Russell Martin More About Methods 30 / 81

29 The return Keyword // program to demonstrate calling a method that returns // a value import java.util.scanner; public class TestMethodsWithReturnValue { public static void main(string[] args) { System.out.println("The sum is " + sum()); } } public static int sum() { int first, second; // numbers to input Scanner input = new Scanner(System.in); System.out.print("First number? "); first = input.nextint(); System.out.print("Second number? "); second = input.nextint(); return first+second; } Russell Martin More About Methods 31 / 81

30 Remarks $ java TestMethodsWithReturnValue First number? 10 Second number? 5 The sum is 15 $ The invocation to sum() in the main program creates a new execution environment with its own memory, allocates space in this memory for the variables defined inside the method, and starts executing the method s code. The statement return expression is used to assign a value to the method and return the control to the calling method. If the method type is void there is no need to use a return statement, but one may be used to force the control back to the calling method. It is syntactically legal to have many return statements inside a method... but not a very good practice for maintenance as it may become difficult to trace all of them. Russell Martin More About Methods 32 / 81

31 Parameters Methods can receive data from the calling method in several ways. We will comment on each of the available possibilities by referring to the same basic piece of code. Russell Martin More About Methods 33 / 81

32 Class or Instance Variables // program to demonstrate calling a method that // uses class or instance variables. import java.util.scanner; public class TestMethodsWithClassVars { private static int first, second; // numbers to input public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("First number? "); first = input.nextint(); System.out.print("Second number? "); second = input.nextint(); System.out.println("Sum of numbers is " + sum()); System.out.println("First number is now " + first); } } public static int sum() { first = first + second; return first; } Russell Martin More About Methods 34 / 81

33 Remarks As first and second are class variables they are accessible throughout the class, even in the method sum(). Assigning first + second to first in sum() means the value of first will have changed in the main method. What is output if we input 10 and 5? The static modifier was added to the declarations of first and second otherwise Java would complain as follows: TestMethodsWithReturnValue.java:12: non-static variable first cannot be referenced from a static context first = input.nextint(); ˆ What happens if the declarations of first and second are moved inside main? Russell Martin More About Methods 35 / 81

34 Method Parameters // program to demonstrate calling a method that receives its // data through a parameter list. import java.util.scanner; public class TestMethodsWithParameterPassing { public static int first, second; // numbers to input public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("First number? "); first = input.nextint(); System.out.print("Second number? "); second = input.nextint(); System.out.println("Sum of numbers is " + sum(first, second)); System.out.println("First number is now " + first); } public static int sum( int f, int s) { f = f+s; return f; } } Russell Martin More About Methods 38 / 81

35 Remarks How do things work in this case? Here parameters are variables of primitive data type. The parameter list in the method call must contain the same number of elements, in the same order and of the same type as the parameter list in the method definition. When sum(first, second) is called from the main method the values of the actual parameters (first and second) are evaluated and copied as values for the formal parameters (f and s). This is known as passing by value. Any changes to the formal parameters (assigning f+s to f) will not affect the actual parameters, i.e. here first and second are not affected by the method call. Question: what would happen if the parameters were called first and second? Russell Martin More About Methods 39 / 81

36 Reference Parameters I Note that for items of data that are stored by reference (e.g. objects or arrays), the parameter mechanism has slightly different effects. In such cases the actual address of the variable is passed to the calling method. Consequently, any change that happens to the parameters inside the called method will remain after the control is returned to the caller. This is similar to what happens when we assign one object to another. Rectangle rect2 = new Rectangle(); Rectangle bigrect = new Rectangle(100,35); rect2 = bigrect; Both bigrect and rect2 will refer to the same object. Russell Martin More About Methods 41 / 81

37 Reference Parameters II public class TestMethodsWithObjectParameters { // METHODS /* Main Method */ public static void main(string[] args) { // Instantiate up bigrect Rectangle bigrect = new Rectangle(100,35); // Print out its length and width System.out.println("The Big Rectangle s dimensions"); bigrect.printdimensions(); // Call changerectangle using bigrect as parameter and print Rectangle newrect = changerectangle(bigrect); System.out.println("After calling changerectangle(bigrect) "); newrect.printdimensions(); Russell Martin More About Methods 42 / 81

38 Reference Parameters III } // Print out the Big Rectangle s length and width again System.out.println("The Big Rectangle s dimensions "); bigrect.printdimensions(); } public static Rectangle changerectangle(rectangle therect) { therect.setlength(50); return therect; } This has the following output: $ java TestMethodsWithObjectParameters The Big Rectangle s dimensions Length: 100 Width: 35 After calling changerectangle(bigrect) Length: 50 Width: 35 The Big Rectangle s dimensions Length: 50 Width: 35 $ Russell Martin More About Methods 43 / 81

39 Reference Parameters IV bigrect length = 100 width =35 bigrect length = 50 width =35 bigrect length = 100 width =35 therect therect bigrect length = 50 width = 35 newrect Russell Martin More About Methods 44 / 81

40 Scope and Lifetime of Identifiers 1 The scope of an identifier refers to the region of a program in which an identifier can be used. 2 An identifier with class scope is accessible throughout the entire class and anywhere in the program where an object X of the given class is defined, prefixed by X. (dependent on modifiers e.g. public). 3 A block is any segment of code beginning with a { and ending with a }. 4 An identifier with block or local scope is accessible from its point of declaration throughout the entire block in which it is defined. Russell Martin More About Methods 45 / 81

41 Remarks Method parameters can be thought of as having block or local scope. They are only accessible within the body of the method they refer to. Class attributes are examples of variables having class scope. Method names give another example of identifiers having class scope. Russell Martin More About Methods 46 / 81

42 Scope of Identifiers // program to demonstrate calling a method that receives its // data through a parameter list. import java.util.scanner; class TestMethodsWithParameterPassing { private static int first, second; // numbers to input public static void main(string[] args) { System.out.print("First number? "); first = new Scanner(System.in).nextInt(); System.out.print("Second number? "); second = new Scanner(System.in).nextInt(); System.out.println("Sum of numbers is " + sum1(first, second)); System.out.println("First number is now " + first); } first, second and sum() have class scope } public static int sum( int f, int s) { f = f+s; return f; } f, s have local or block scope Russell Martin More About Methods 47 / 81

43 Lifetime The lifetime of an identifier is the period during which the value of the identifier exists in the computer memory. identifiers with block scope only exist during the execution of the particular block. When an object goes out of scope, garbage collection takes place. (Garbage collection is the process of reclaiming memory for re-use.) Russell Martin More About Methods 48 / 81

44 Back to the Swimming Pool Recall we had the following pseudocode for the method timetofill located in the SwimmingPool class. METHOD timetofill INPUT OUTPUT double COMPUTE the volume of the pool poolvolume as length x width x depth RETURN (poolvolume x UNITCAPACITY) / RATEOFFLOW Russell Martin More About Methods 49 / 81

45 Implementation of the method TimeToFill() /** * Compute the pool s volume as the result of * volume x UNITCAPACITY / RATEOFFLOW * and return double */ public double timetofill( ) { double mypool; } mypool = length * width * depth; return mypool * UNITCAPACITY / RATEOFFLOW; Russell Martin More About Methods 50 / 81

46 FuelCost: Pseudocode for totalcost and averagecost METHOD totalcost INPUT OUTPUT double COMPUTE the total fuel cost as moncost + tuescost + wedcost + thurscost + fricost RETURN the computed value METHOD averagecost INPUT OUTPUT double CALL totalcost() to obtain the total cost of fuel COMPUTE totalcost() / 5 RETURN the computed value How can we implement these? Russell Martin More About Methods 51 / 81

47 Summary We had a closer look at methods with respect to flow of control and parameter passing. We mentioned scope of lifetime of identifiers. We gave the implementation of the timetofill() method from the SwimmingPool class. Russell Martin More About Methods 53 / 81

48 Lecture 12 Arithmetic and the Math Class COMP101: Introduction to Programming in JAVA Morelli chapter 5, Cohoon and Davidson Chapter 2 Russell Martin with some materials from Clare Dixon, Michele Zito, and Frans Coenen Department of Computer Science Russell.Martin(at)liv.ac.uk www2.csc.liv.ac.uk/ martin/teaching/comp101 Russell Martin Arithmetic and the Math Class 54 / 81

49 Overview We introduce some of the features of the Math Class. We consider the analysis and design, implementation and testing of a program to calculate area and circumference of a circle given its radius. We discuss arithmetic testing with respect to this program. Russell Martin Arithmetic and the Math Class 55 / 81

50 Expressions Java supports the standard binary algebraic operators +, -, and / (plus the remainder operator). Recall that Java expressions may look different from their algebraic counterpart: Operator Java Algebra + x+2 x m-2 m 2 m * 2 2m or 2 m x / x / y x y or y remainder x % y x mod y Russell Martin Arithmetic and the Math Class 56 / 81

51 Division and Remainder Recall when applied to two integers / uses integer division. The result is the integer part of the usual division result. In Java 11/2 evaluates to 5, 6/2 evaluates to 3 as does 7/2. x % y gives the remainder after dividing x by y. In Java 11 % 2 evaluates to 1, 6 % 2 evaluates to 0, and 7 % 2 evaluates to 1. What is the result of 12/6 and 13/6? What is the result of 12 % 6 and 13 % 6? Russell Martin Arithmetic and the Math Class 57 / 81

52 Abbreviations: The Increment Operators Java provides a number of unary operators that are used to increment or decrement an integer variable. So k++ (or, resp. k--) has the effect of adding (resp. subtracting) one to (from) the variable k and assigning the resulting value to k. Both ++k and k++ (or --k and k--) are valid increment expressions, but with different meanings: here s the explanation in the case of positive increment, The expression j = ++k corresponds to an increment of k and then the assignment of the resulting value to j. On the other hand in j = k++ the initial value of k is assigned to variable j first and then k is increased. Be careful when using these. Russell Martin Arithmetic and the Math Class 58 / 81

53 Other Shortcut Operators Similarly, Java supplies a number of shortcut assignment operators. Their format and interpretation is given in the following table: concise form a += b a -= b a *= b a /= b a %= b equivalent verbose expression a = a + b a = a - b a = a * b a = a / b a = a % b Note that expressions such as a =* b are not allowed. Russell Martin Arithmetic and the Math Class 60 / 81

54 Operator Precedence In the next table the operators we have seen so far are listed according to precedence order, the closer to the top of the table, the higher its precedence. Operators with higher precedence are evaluated before operators with lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression all binary operators, except for the assignment operators, are evaluated from left to right; assignment operators are evaluated right to left. Russell Martin Arithmetic and the Math Class 61 / 81

55 Operator Precedence Operators Precedence postfix expr++ expr-- unary ++expr --expr multiplicative * / % additive + - assignment = += -= *= /= %= Thus result = 3 * will evaluate to the same as result = ((3 * 8) + 2). To ensure clarity and prevent errors, use parentheses. Russell Martin Arithmetic and the Math Class 62 / 81

56 Dividing by Zero When programming, always take care to avoid dividing by zero. In Java System.out.println("5 /0 " + 5/ 0); will result in the following run-time error. Exception in thread "main" java.lang.arithmeticexception: / by zero at TestNaN.main(TestNaN.java:41) System.out.println("5.0 / 0.0 " / 0.0); System.out.println("0.0 / 0.0 " / 0.0); will result in 5.0 / 0.0 Infinity 0.0 / 0.0 NaN NaN is short for is not a number. Russell Martin Arithmetic and the Math Class 63 / 81

57 The Math class More advanced mathematical computations can be achieved using operations defined in the Math class. This class is contained in the java.lang package, included implicitly in all Java programs (no explicit import needed!). The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions. The Math class cannot be instantiated and all its methods are static class methods. Hence, they are invoked through the class name e.g. Math.round(34.2) to call the method round. For more details, see docs.oracle.com/javase/8/docs/api/java/lang/math.html Russell Martin Arithmetic and the Math Class 64 / 81

58 Approximation Functions double ceil(double a) Returns the smallest double value that is greater than or equal to the argument and is equal to a mathematical integer. E.g. Math.ceil(10.2) returns 11.0 double floor(double a) Returns the greatest double value that is less than or equal to the argument and is equal to a mathematical integer. E.g. Math.floor(10.2) returns 10.0 long round(double a) (int) Returns the long integer closest to its argument. E.g. Math.round(10.2) returns 10 double rint(double a) Returns the double value that is closest in value to the argument and is equal to a mathematical integer. E.g. Math.rint(10.2) returns 10.0 Russell Martin Arithmetic and the Math Class 65 / 81

59 Abs, Max, Min double abs(double a) It returns the absolute value of its input. E.g. Math.abs( ) returns and Math.abs(743.97) returns double max(double a, double b) Returns the greater of a and b. E.g. Math.max(543.2,532.0) returns double min(double a, double b) Returns the smaller of a and b. E.g. Math.min(543.2,532.0) returns Note abs, max, min also have versions for int, long and float which take and return parameters of the appropriate types. Russell Martin Arithmetic and the Math Class 67 / 81

60 Powers, Square Roots etc double pow(double a, double b) The expression Math.pow(a,b) computes and returns the value a b (as a double). double sqrt(double a) Returns the square root of its argument. E.g. Math.sqrt(25.0) returns 5.0 double cbrt(double a) Returns the cube root of its argument. E.g. Math.cbrt(8.0) returns 2.0 Russell Martin Arithmetic and the Math Class 68 / 81

61 Trigonometric functions double sin(double a) Returns the trigonometric sine of its argument (considered as an angle measured in radians). double cos(double a) Returns the trigonometric cosine of its argument (considered as an angle measured in radians). double tan(double a) Returns the trigonometric tangent of its argument (considered as an angle measured in radians). double double todegrees(double angrad) Converts an angle measured in radians to an approximately equivalent angle measured in degrees. toradians(double angdeg) Converts an angle measured in degrees to an approximately equivalent angle measured in radians. Russell Martin Arithmetic and the Math Class 69 / 81

62 More About the Math class Many other trigonometric functions, e.g. the inverse functions asin, acos, and atan are also provided. The following useful numbers are denoted by the constants in the Math class: e = is Math.E; and π = is Math.PI. This is only a very short review of the Math class. We did not cover all its methods and even when we did cover a method, we only provided a very short description of its behaviour. For more details read the full description available from docs.oracle.com/javase/8/docs/api/java/lang/math.html Russell Martin Arithmetic and the Math Class 70 / 81

63 Example: Circle Calculation Problem Write a program that calculates and outputs the circumference and area of a circle given its radius. radius Hints: assume that the radius is input by the user as a double; the area of a circle = π radius 2 ; Circumference = π diameter = 2 π radius; Use the constant PI from the Math class. Russell Martin Arithmetic and the Math Class 71 / 81

64 Class Analysis Very little analysis needed. The statement talks of a Circle (a class) which has a radius (an attribute). The system is supposed to calculate the circumference and the area of the circle. The use of the word calculate should lead us to believe that we will need to define methods for doing this. We assume that Circle does the relevant calculations, and we have a CircleUser class that allows the input of the circumference, instantiates Circle, and displays the results of the calculations. A possible class diagram is on the next slide. Russell Martin Arithmetic and the Math Class 72 / 81

65 Class Diagram CircleUser + main(string[]) Circle - radius: double +circumference(): double +area(): double Note that we are assigning the responsibility of computing circumference and area of the circle to the Circle class. Russell Martin Arithmetic and the Math Class 73 / 81

66 Processing The main method has the usual simple task of setting up all relevant variables, then calling the area and circumference methods, and finally displaying the result of the computation. METHOD main INPUT args OUTPUT LOCAL DATA rad READ rad from the keyboard SET up an instance mycircle of Circle using rad as radius of the structure PRINT the result of calculating the circumference and area of mycircle Russell Martin Arithmetic and the Math Class 74 / 81

67 Active Behaviours The class Circle is responsible for computing the circumference and the area of the circle Recall that the circumference of a circle having radius r is 2 π r, whereas the area of the circle is πr 2. We will not need to write any pseudocode for this. When this will become Java code, we may use the constant Math.PI to get an (approximate) value for π = , and we may use Math.pow to compute r 2 needed in the formula for the area of the circle, or we could just use the expression radius * radius. Russell Martin Arithmetic and the Math Class 75 / 81

68 The Circle Class /** * Circle.java - michele * Fri Oct :36:59 * Edited by Clare Dixon June 2010 **/ public class Circle { // attributes private double radius; // constructors public Circle(double r) { radius = r; } // calculates the circumference of a circle given radius public double circumference() { return 2*Math.PI*radius; } // calculates the area of a circle given radius public double area() { return Math.PI*radius*radius; } } Russell Martin Arithmetic and the Math Class 76 / 81

69 The CircleUser Class /** * CircleUser.java - michele * Fri Oct :35:59 * Edited by Clare Dixon June 2010 **/ import java.util.scanner; public class CircleUser { public static void main(string [] args) { Circle mycircle; Scanner input = new Scanner(System.in); double rad; System.out.print("What s the circle radius? "); rad = input.nextdouble(); mycircle = new Circle(rad); System.out.println("Circumference = " + mycircle.circumference()); System.out.println("Area = " + mycircle.area()); } } Russell Martin Arithmetic and the Math Class 77 / 81

70 Arithmetic Testing Given an arithmetic statement, it is always a good idea to test the effect that negative, positive and zero sample values will have on the outcome. In this case, there is only one numeric input, we should therefore test, negative and positive inputs as well as zero. If there is more than one input, we should test every possible combination of positive, negative and zero input. Thus, if we have two inputs we would have 3 3 possible combinations, with three inputs possible combinations (and so on). This form of testing is known as arithmetic testing. Russell Martin Arithmetic and the Math Class 78 / 81

71 Arithmetic Testing: The Circle Test Case Expected Result Radius Circumference Area Note that when we input a negative number we produce a negative circumference - this is probably not the desired result. We should return to the requirements phase and determine what action we should take in the event of a negative radius. What might this be? However, with our current level of programming skills, we will just have to live with this undesirable result. Russell Martin Arithmetic and the Math Class 79 / 81

72 Arithmetic Testing: Output The following is the actual output. $ java CircleUser What s the circle radius? 10.0 Circumference = Area = $ java CircleUser What s the circle radius? 0.0 Circumference = 0.0 Area = 0.0 $ java CircleUser What s the circle radius? Circumference = Area = $ How could we improve on the presentation of this output? Russell Martin Arithmetic and the Math Class 80 / 81

73 Summary We introduced some of the features of the Math Class We considered the analysis and design of a program to calculate some values of a circle given its radius. We gave the implementation of these classes. We discussed arithmetic testing with respect to our program. Russell Martin Arithmetic and the Math Class 81 / 81

CS110: PROGRAMMING LANGUAGE I

CS110: PROGRAMMING LANGUAGE I CS110: PROGRAMMING LANGUAGE I Computer Science Department Lecture 8: Methods Lecture Contents: 2 Introduction Program modules in java Defining Methods Calling Methods Scope of local variables Passing Parameters

More information

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i

More information

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a, The (Outsource: Supplement) The includes a number of constants and methods you can use to perform common mathematical functions. A commonly used constant found in the Math class is Math.PI which is defined

More information

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug, 1 To define methods, invoke methods, and pass arguments to a method ( 5.2-5.5). To develop reusable code that is modular, easy-toread, easy-to-debug, and easy-to-maintain. ( 5.6). To use method overloading

More information

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 12. Numbers Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Numeric Type Conversions Math Class References Numeric Type Conversions Numeric Data Types (Review) Numeric Type Conversions Consider

More information

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class

The Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class The (Outsource: Supplement) The includes a number of constants and methods you can use to perform common mathematical functions. A commonly used constant found in the Math class is Math.PI which is defined

More information

Chapter 6 Methods. Dr. Hikmat Jaber

Chapter 6 Methods. Dr. Hikmat Jaber Chapter 6 Methods Dr. Hikmat Jaber 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i

More information

Chapter 5 Methods / Functions

Chapter 5 Methods / Functions Chapter 5 Methods / Functions 1 Motivations A method is a construct for grouping statements together to perform a function. Using a method, you can write the code once for performing the function in a

More information

DUBLIN CITY UNIVERSITY

DUBLIN CITY UNIVERSITY DUBLIN CITY UNIVERSITY REPEAT EXAMINATIONS 2008 MODULE: Object-oriented Programming I - EE219 COURSE: B.Eng. in Electronic Engineering (Year 2 & 3) B.Eng. in Information Telecomms Engineering (Year 2 &

More information

DUBLIN CITY UNIVERSITY

DUBLIN CITY UNIVERSITY DUBLIN CITY UNIVERSITY SEMESTER ONE EXAMINATIONS 2007 MODULE: Object Oriented Programming I - EE219 COURSE: B.Eng. in Electronic Engineering B.Eng. in Information Telecommunications Engineering B.Eng.

More information

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i

More information

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi Chapter 4 Loops for while do-while Last Week Chapter 5 Methods Input arguments Output Overloading Code reusability Scope of

More information

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. Chapter 5 Methods rights reserved. 0132130807 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. rights reserved. 0132130807 2 1 Problem int sum =

More information

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2

More information

Lecture 11. Example 1. Introduction. Method definition and invocation. Parameter passing: value vs. reference parameters. Scope and Lifetime.

Lecture 11. Example 1. Introduction. Method definition and invocation. Parameter passing: value vs. reference parameters. Scope and Lifetime. Lecture 11 Example 1 Method definition and invocation. Parameter passing: value vs. reference parameters. Scope and Lifetime. Constructors Material from Holmes Chapter 6: sections 1 through to 8, except

More information

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

Chapter 5 Methods. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk Chapter 5 Methods Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk ١ Introducing Methods A method is a collection of statements that

More information

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; } Chapter 5 Methods 5.1 Introduction A method is a collection of statements that are grouped together to perform an operation. You will learn how to: o create your own mthods with or without return values,

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Primitive Data Types: Intro

Primitive Data Types: Intro Primitive Data Types: Intro Primitive data types represent single values and are built into a language Java primitive numeric data types: 1. Integral types (a) byte (b) int (c) short (d) long 2. Real types

More information

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington First Programs CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Output System.out.println( ) prints out something. System.out.println is the first

More information

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington First Programs CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Output System.out.println( ) prints out something. System.out.println is the first

More information

JAVA Programming Concepts

JAVA Programming Concepts JAVA Programming Concepts M. G. Abbas Malik Assistant Professor Faculty of Computing and Information Technology University of Jeddah, Jeddah, KSA mgmalik@uj.edu.sa Find the sum of integers from 1 to 10,

More information

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination Tuesday, November 3, 2009 Examiners: Mathieu Petitpas

More information

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operators Overview Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operands and Operators Mathematical or logical relationships

More information

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington First Programs CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Output System.out.println( ) prints out something. System.out.println is the first

More information

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI Outline Chapter 3 Using APIs 3.1 Anatomy of an API 3.1.1 Overall Layout 3.1.2 Fields 3.1.3 Methods 3.2 A Development Walkthrough 3.2.1 3.2.2 The Mortgage Application 3.2.3 Output Formatting 3.2.4 Relational

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Mathematical Functions Java provides many useful methods in the Math class for performing common mathematical

More information

CT 229 Java Syntax Continued

CT 229 Java Syntax Continued CT 229 Java Syntax Continued 06/10/2006 CT229 Lab Assignments Due Date for current lab assignment : Oct 8 th Before submission make sure that the name of each.java file matches the name given in the assignment

More information

4. Java Project Design, Input Methods

4. Java Project Design, Input Methods 4-1 4. Java Project Design, Input Methods Review and Preview You should now be fairly comfortable with creating, compiling and running simple Java projects. In this class, we continue learning new Java

More information

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education AP Computer Science Return values, Math, and double Distance between points Write a method that given x and y coordinates for two points prints the distance between them If you can t do all of it, pseudocode?

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only

More information

Object-Based Programming. Programming with Objects

Object-Based Programming. Programming with Objects ITEC1620 Object-Based Programming g Lecture 8 Programming with Objects Review Sequence, Branching, Looping Primitive datatypes Mathematical operations Four-function calculator Scientific calculator Don

More information

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Numerical Data CS 180 Sunil Prabhakar Department of Computer Science Purdue University Problem Write a program to compute the area and perimeter of a circle given its radius. Requires that we perform operations

More information

Chapter 4: Basic C Operators

Chapter 4: Basic C Operators Chapter 4: Basic C Operators In this chapter, you will learn about: Arithmetic operators Unary operators Binary operators Assignment operators Equalities and relational operators Logical operators Conditional

More information

Chapter 4 Mathematical Functions, Characters, and Strings

Chapter 4 Mathematical Functions, Characters, and Strings Chapter 4 Mathematical Functions, Characters, and Strings Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations Suppose you need to estimate

More information

CEN 414 Java Programming

CEN 414 Java Programming CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea

More information

C Programs: Simple Statements and Expressions

C Programs: Simple Statements and Expressions .. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar.. C Programs: Simple Statements and Expressions C Program Structure A C program that consists of only one function has the following

More information

Lecture 5: Methods CS2301

Lecture 5: Methods CS2301 Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int

More information

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A CSC 1051 Algorithms and Data Structures I Midterm Examination February 25, 2016 Name: KEY A Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in

More information

AP Computer Science A. Return values

AP Computer Science A. Return values AP Computer Science A Return values Distance between points Write a method that given x and y coordinates for two points prints the distance between them Pseudocode? Java's Math class Method name Math.abs(value)

More information

Chapter 2. Elementary Programming

Chapter 2. Elementary Programming Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-2: Return; doubles and casting reading: 3.2, 4.1 videos: Ch. 3 #2 Copyright 2009 by Pearson Education Finish Car example Lecture outline Returns Java Math library

More information

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, import, new 1 class Lecture2 { 2 3 Data types, Variables, and Operators 4 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 45

More information

VBScript: Math Functions

VBScript: Math Functions C h a p t e r 3 VBScript: Math Functions In this chapter, you will learn how to use the following VBScript functions to World Class standards: 1. Writing Math Equations in VBScripts 2. Beginning a New

More information

Benefits of Methods. Chapter 5 Methods

Benefits of Methods. Chapter 5 Methods Chapter 5 Methods Benefits of Methods Write a method once and reuse it anywhere. Information hiding: hide the implementation from the user Reduce complexity 1 4 Motivating Example Often we need to find

More information

1001ICT Introduction To Programming Lecture Notes

1001ICT Introduction To Programming Lecture Notes 1001ICT Introduction To Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 1, 2015 1 M Environment console M.1 Purpose This environment supports programming

More information

Methods CSC 121 Spring 2017 Howard Rosenthal

Methods CSC 121 Spring 2017 Howard Rosenthal Methods CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

Information Science 1

Information Science 1 Topics covered Information Science 1 Terms and concepts from Week 8 Simple calculations Documenting programs Simple Calcula,ons Expressions Arithmetic operators and arithmetic operator precedence Mixed-type

More information

CSC Algorithms and Data Structures I. Midterm Examination February 25, Name:

CSC Algorithms and Data Structures I. Midterm Examination February 25, Name: CSC 1051-001 Algorithms and Data Structures I Midterm Examination February 25, 2016 Name: Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

Methods CSC 121 Fall 2016 Howard Rosenthal

Methods CSC 121 Fall 2016 Howard Rosenthal Methods CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

COMP 202 Java in one week

COMP 202 Java in one week CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

More information

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1 Chapter 2 Input, Processing, and Output Fall 2016, CSUS Designing a Program Chapter 2.1 1 Algorithms They are the logic on how to do something how to compute the value of Pi how to delete a file how to

More information

1.1 Your First Program

1.1 Your First Program 1.1 Your First Program 1 Why Programming? Why programming? Need to tell computer what you want it to do. Naive ideal. Natural language instructions. Please simulate the motion of these heavenly bodies,

More information

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University Mathematical Functions, Characters, and Strings CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Static methods Remember the main method header? public static void

More information

1.1 Your First Program! Naive ideal. Natural language instructions.

1.1 Your First Program! Naive ideal. Natural language instructions. Why Programming? Why programming? Need to tell computer what you want it to do. 1.1 Your First Program Naive ideal. Natural language instructions. Please simulate the motion of these heavenly bodies, subject

More information

www.thestudycampus.com Methods Let s imagine an automobile factory. When an automobile is manufactured, it is not made from basic raw materials; it is put together from previously manufactured parts. Some

More information

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87 Data Types Java is a strongly-typed 1 programming language. Every variable has a type. Also, every (mathematical) expression has a type. There are two categories of data types: primitive data types, and

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements More Things We Can Do With It! More operators and expression types More s 11 October 2007 Ariel Shamir 1 Overview Variables and declaration More operators and expressions String type and getting input

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

1.1 Your First Program

1.1 Your First Program Why Programming? 1.1 Your First Program Why programming? Need to tell computer what you want it to do. Naive ideal. Natural language instructions. Please simulate the motion of these heavenly bodies, subject

More information

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY Arithmetic Operators There are four basic arithmetic operations: OPERATOR USE DESCRIPTION + op1 + op2 Adds op1 and op2 - op1 + op2 Subtracts

More information

Expressions and operators

Expressions and operators Mathematical operators and expressions The five basic binary mathematical operators are Operator Operation Example + Addition a = b + c - Subtraction a = b c * Multiplication a = b * c / Division a = b

More information

I. Variables and Data Type week 3

I. Variables and Data Type week 3 I. Variables and Data Type week 3 variable: a named memory (i.e. RAM, which is volatile) location used to store/hold data, which can be changed during program execution in algebra: 3x + 5 = 20, x = 5,

More information

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2010) - All Sections Midterm Examination

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2010) - All Sections Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202B - Introduction to Computing I (Winter 2010) - All Sections Midterm Examination Thursday, March 11, 2010 Examiners: Milena Scaccia

More information

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name: CSC 1051 Algorithms and Data Structures I Midterm Examination October 7, 2013 Name: Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the spaces

More information

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 9, Name: KEY

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 9, Name: KEY CSC 1051 Algorithms and Data Structures I Midterm Examination October 9, 2014 Name: KEY Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the

More information

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University Mathematical Functions, Characters, and Strings CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Static methods Remember the main method header? public static void

More information

Information Science 1

Information Science 1 Information Science 1 Simple Calcula,ons Week 09 College of Information Science and Engineering Ritsumeikan University Topics covered l Terms and concepts from Week 8 l Simple calculations Documenting

More information

Calculations, Formatting and Conversions

Calculations, Formatting and Conversions Chapter 5 Calculations, Formatting and Conversions What is in This Chapter? In this chapter we discuss how to do basic math calculations as well as use some readily available Math functions in JAVA. We

More information

IEEE Floating-Point Representation 1

IEEE Floating-Point Representation 1 IEEE Floating-Point Representation 1 x = ( 1) s M 2 E The sign s determines whether the number is negative (s = 1) or positive (s = 0). The significand M is a fractional binary number that ranges either

More information

Welcome to the Primitives and Expressions Lab!

Welcome to the Primitives and Expressions Lab! Welcome to the Primitives and Expressions Lab! Learning Outcomes By the end of this lab: 1. Be able to define chapter 2 terms. 2. Describe declarations, variables, literals and constants for primitive

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 5 Anatomy of a Class Outline Problem: How do I build and use a class? Need to understand constructors A few more tools to add to our toolbox Formatting

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise

More information

Java Classes: Math, Integer A C S L E C T U R E 8

Java Classes: Math, Integer A C S L E C T U R E 8 Java Classes: Math, Integer A C S - 1903 L E C T U R E 8 Math class Math class is a utility class You cannot create an instance of Math All references to constants and methods will use the prefix Math.

More information

Introduction to Computer Science and Object-Oriented Programming

Introduction to Computer Science and Object-Oriented Programming COMP 111 Introduction to Computer Science and Object-Oriented Programming Values Judgment Programs Manipulate Values Inputs them Stores them Calculates new values from existing ones Outputs them In Java

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-2: Return values, Math, and double reading: 3.2, 2.1-2.2 Copyright 2011 by Pearson Education 2 Method name Math.abs(value) Math.ceil(value) Math.floor(value)

More information

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5. Week 2: Console I/O and Operators Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.1) CS 1428 Fall 2014 Jill Seaman 1 2.14 Arithmetic Operators An operator is a symbol that tells the computer to perform specific

More information

Simple Java Reference

Simple Java Reference Simple Java Reference This document provides a reference to all the Java syntax used in the Computational Methods course. 1 Compiling and running... 2 2 The main() method... 3 3 Primitive variable types...

More information

Chapter 4: Conditionals and Recursion

Chapter 4: Conditionals and Recursion Chapter 4: Conditionals and Recursion Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Agenda The modulus operator Random Number Generation Conditional Execution Alternative

More information

Unit 3. Operators. School of Science and Technology INTRODUCTION

Unit 3. Operators. School of Science and Technology INTRODUCTION INTRODUCTION Operators Unit 3 In the previous units (unit 1 and 2) you have learned about the basics of computer programming, different data types, constants, keywords and basic structure of a C program.

More information

Chapter 7. Iteration. 7.1 Multiple assignment

Chapter 7. Iteration. 7.1 Multiple assignment Chapter 7 Iteration 7.1 Multiple assignment You can make more than one assignment to the same variable; effect is to replace the old value with the new. int bob = 5; System.out.print(bob); bob = 7; System.out.println(bob);

More information

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

1 class Lecture5 { 2 3 Methods / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 1 class Lecture5 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199 Methods 2 Methods can be used to define reusable code, and organize

More information

The return Statement

The return Statement The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 7: Return values, Math, and casting reading: 3.2, 2.1-2.2 (Slides adapted from Stuart Reges, Hélène Martin, and Marty Stepp) Copyright 2011 by Pearson Education

More information

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein PRIMITIVE VARIABLES CS302 Introduction to Programming University of Wisconsin Madison Lecture 3 By Matthew Bernstein matthewb@cs.wisc.edu Variables A variable is a storage location in your computer Each

More information

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Basic Operations jgrasp debugger Writing Programs & Checkstyle Basic Operations jgrasp debugger Writing Programs & Checkstyle Suppose you wanted to write a computer game to play "Rock, Paper, Scissors". How many combinations are there? Is there a tricky way to represent

More information

Using Free Functions

Using Free Functions Chapter 3 Using Free Functions 3rd Edition Computing Fundamentals with C++ Rick Mercer Franklin, Beedle & Associates Goals Evaluate some mathematical and trigonometric functions Use arguments in function

More information

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will

More information

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 Announcements Slides will be posted before the class. There might be few

More information

Lecture 6: While Loops and the Math Class

Lecture 6: While Loops and the Math Class Lecture 6: While Loops and the Math Class Building Java Programs: A Back to Basic Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. while loops 2 Categories of loops

More information

Elementary Programming

Elementary Programming Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal

More information

S8.6 Volume. Section 1. Surface area of cuboids: Q1. Work out the surface area of each cuboid shown below:

S8.6 Volume. Section 1. Surface area of cuboids: Q1. Work out the surface area of each cuboid shown below: Things to Learn (Key words, Notation & Formulae) Complete from your notes Radius- Diameter- Surface Area- Volume- Capacity- Prism- Cross-section- Surface area of a prism- Surface area of a cylinder- Volume

More information

What did we talk about last time? Examples switch statements

What did we talk about last time? Examples switch statements Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

More information

6.001 Notes: Section 6.1

6.001 Notes: Section 6.1 6.001 Notes: Section 6.1 Slide 6.1.1 When we first starting talking about Scheme expressions, you may recall we said that (almost) every Scheme expression had three components, a syntax (legal ways of

More information

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods Encapsulation You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods external - the interaction of the object with other objects in the program

More information

COMP 202. Java in one week

COMP 202. Java in one week COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language

More information