Benefits of Methods. Chapter 5 Methods

Similar documents
Chapter 5 Methods / Functions

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

Chapter 6 Methods. Dr. Hikmat Jaber

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

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.

CS115 Principles of Computer Science

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

CS110: PROGRAMMING LANGUAGE I

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

JAVA Programming Concepts

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

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

Methods. CSE 114, Computer Science 1 Stony Brook University

Chapter 6: Methods. Objectives 9/21/18. Opening Problem. Problem. Problem. Solution. CS1: Java Programming Colorado State University

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

Lecture 5: Methods CS2301

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

CS-201 Introduction to Programming with Java

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

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

Lecture #6-7 Methods

int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to 10 is " + sum);

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

Chapter 4 Mathematical Functions, Characters, and Strings

Introduction to programming using Python

Expressions and operators

DUBLIN CITY UNIVERSITY

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

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

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

DUBLIN CITY UNIVERSITY

Primitive Data Types: Intro

CS-201 Introduction to Programming with Java

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

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

CS1150 Principles of Computer Science Methods

Lecture 2:- Functions. Introduction

CS1150 Principles of Computer Science Methods

(2-2) Functions I H&K Chapter 3. Instructor - Andrew S. O Fallon CptS 121 (January 18, 2019) Washington State University

Chapter 4. Mathematical Functions, Characters, and Strings

Using Free Functions

Procedural Abstraction and Functions That Return a Value. Savitch, Chapter 4

C Programs: Simple Statements and Expressions

CS110D: PROGRAMMING LANGUAGE I

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

CS171:Introduction to Computer Science II

Programming in C Quick Start! Biostatistics 615 Lecture 4

Preview from Notesale.co.uk Page 2 of 79

The following list represents the written codes in order:

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

COMP 111 PROGRAMMING I MODULARITY USING FUNCTIONS

Methods: A Deeper Look

JVM (java) compiler. A Java program is either a library of static methods (functions) or a data type definition

CS101 Introduction to computing Function, Scope Rules and Storage class

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

ECE 122. Engineering Problem Solving with Java

ECET 264 C Programming Language with Applications

1.1 Your First Program

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

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

1.1 Your First Program

EECS402 Lecture 02. Functions. Function Prototype

Chapter 3 Function Overloading

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

Methods (Deitel chapter 6)

Programmierpraktikum

Methods (Deitel chapter 6)

Methods CSC 121 Spring 2017 Howard Rosenthal

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

Methods CSC 121 Fall 2016 Howard Rosenthal

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

9 C Language Function Block

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.

AP CS Unit 3: Control Structures Notes

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

Functions. Systems Programming Concepts

Introduction to C Final Review Chapters 1-6 & 13

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

6. C++ Subprograms David Keil CS I slides 7/03 1

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

The return Statement

Module 4: Characters, Strings, and Mathematical Functions

Lab Instructor : Jean Lai

Methods CSC 121 Fall 2014 Howard Rosenthal

CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions

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

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

Transcription:

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 the maximum between two numbers A method is a construct for grouping statements together to perform a function. A method is defined and implemented once but can be used repeatedly A method can be used as a blackbox Defining and Using Methods Define a method give a definition of what the method is to do modifier returntype methodname(list of parameters) { collection of statements; Call or invoke a method use a method methodname(list of parameters) 5 Method Abstraction Method abstraction a black box that contains the detailed implementation for the method. Return Value Type A method may return a value (int, double, char, String, ) value-returning method A method may perform desired operations without returning a value (void) void method 3 6

Method Signature Method signature The combination of the method name and the parameter list main method The main method is a method that s invoked by JVM The main method s header is always the same //method body The statements in main method may invoke other methods that are defined in the class or in other classes Hello World! ); int number = (int) (Math.random()*100); 7 Parameters The variables defined in the method header are known as formal parameters When invoking a method, a value is passed to the parameter and this value is referred to as actual parameter or argument. The arguments must match the parameters in order, number, and compatible type Parameters are optional Example A program that defines and uses a method max to return the larger of the two int values TestMax.java 8 11 Method Body The method body contains a collection of statements A return statement is required for a value-returning method Calling Methods pass the value of i pass the value of j 9 12

i is now 5 invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2 13 16 j is now 2 declare variable result 14 17 invoke max(i, j) (num1 > num2) is true since num1 is 5 and num2 is 2 15 18

result is now 5 Execute the print statement 19 22 return result, which is 5 Call Stacks Each time a method is invoked, the system stores parameters and variables in an area of memory, known as a stack When a method calls another method, the caller's stack space is kept intact New space is created to handle the new method call When a method finishes, its associated space is released. 20 23 return max(i, j) and assign the return value to k i is declared and initialized 21 24

j is declared and initialized pass the values of i and j to num1 and num2 25 28 Declare k pass the values of i and j to num1 and num2 26 29 Invoke max(i, j) (num1 > num2) is true 27 30

31 Assign num1 to result CAUTION A return statement is required for a value-returning method Compiler error when it is possible that a method does not return a value public static int sign(int x) { if (x < 0) { return -1; public static int sign(int x) { if (x < 0) { return -1; { return 1; 34 Return result and assign it to k Reuse Methods from Other Classes A method can be invoked from other classes Invoking a static method defined in other classes ClassName.methodName (list of parameters) Example int number = (int) (Math.random()*100); If you create a new class Test, you can invoke the max method using int number = TestMax.max(3,5); 32 35 Execute print statement void Method Example If a method does not return any value, it is said to return void type. The method is called a void method The main method is a void method Hello world! ); Program example defines and uses a method which prints the grade for a given score TestVoidMethod.java 33 36

Passing Parameters When calling a method, the arguments must match the parameters in order, number, and compatible type public static void nprintln(string message, int n) { for (int i = 0; i < n; i++) message); nprintln( Hello!, 3); nprintln( So that s how the methods work, 10); When invoking a method, the value of the argument is passed to the parameter. The variable itself is not affected. This is referred to as pass-by-value. 37 Pass by Value 40 somemethod stack x: 4 main stack x: 3 Pass by Value Trace call stack Pass by Value main stack x: 3 somemethod stack x: 4 main stack x: 3 38 41 Pass by Value Pass by Value somemethod stack x: 3 main stack x: 3 main stack x: 3 39 42

Program Example - Pass by Value The program demonstrates the effect of pass-by-value It creates a method for swapping two variables The values of the arguments are not changed after the method is invoked What if we change the method to swap(int num1, int num2) TestPassByValue.java Displaying Prime Numbers - Algorithm Set an initial count to 0 (to track the number of prime numbers) Set an initial number to 2 while (count < 50) { test whether number is prime; if number is prime { print the number; update count; Define a method to test whether a number is prime - check whether it is divisible by 2, 3, 4, up to number/2. PrimeNumberMethod.java 43 Modulizing code Write a method once and reuse it anywhere. Methods can be used to reduce redundant code and enable code reuse Methods can also be used to modularize code and reduce complexity of the program Overloading methods Method overloading: multiple methods can have the same name but different parameter lists Compiler determines which method is used based on the method signature (method name and parameters) 44 Problem Revisited: Displaying Prime Numbers Problem: Write a program that displays the first 50 prime numbers in five lines, each of which contains 10 numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. Solution: The problem can be broken into the following tasks: Start with number 1 Determine whether the number is prime. Print the number if it is prime Count the prime numbers so far. If count < 50, repeat the above steps Overloading Methods return num1; return num2; public static double max(double num1, double num2) { return num1; return num2; max(1, 3); max(1.0, 3.0); max(1.0, 3); 45 48

Scope of Local Variables A local variable: a variable defined inside a method Scope: the part of the program where the variable can be referenced The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable A local variable must be declared before it can be used. Scope of Local Variables 49 52 Scope of Local Variables Scope of a Scope of x Scope of a Scope of x 50 int a = 0;... if (a == 1) { int x = 0;... x= + x); int a = 0;... if (a == 1) { int x = 0; //do some calculations on x int x = 2; Error Okay Scope of Local Variables, cont. What does the following method print? public static void method() { int sum = 0; for (int i = 0; i < 5; i++) { int sum = 0; sum += i; sum: + sum); 53 Scope of Local Variables The Math Class Class constants: PI E Class methods: Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods 51 54

Trigonometric Methods min, max, and abs sin(double a) cos(double a) tan(double a) acos(double a) asin(double a) atan(double a) toradians(double degree) todegrees(double radians) Examples: Math.sin(0) //returns 0.0 Math.sin(Math.PI / 6) //returns 0.5 Math.sin(Math.PI / 2) //returns 1.0 Math.cos(0) //returns 1.0 Math.cos(Math.PI / 6) //returns 0.866 Math.cos(Math.PI / 2) //returns 0 max(a, b)and min(a, b) Returns the maximum or minimum of two parameters. abs(a) Returns the absolute value of the parameter. The max, min, and abs methods are overloaded so they work for int, long, float or double 55 58 Exponent Methods exp(double a) Returns e raised to the power of a. log(double a) Returns the natural logarithm of a. log10(double a) Returns the 10-based logarithm of a. pow(double a, double b) Returns a raised to the power of b. sqrt(double a) Returns the square root of a. The random Method random() Generates a random double value greater than or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0). Examples: In general, 56 59 Rounding Methods double ceil(double x) x rounded up to its nearest integer. This integer is returned as a double value. double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value. double round(double x) x is rounded to its nearest integer. Returns (int)math.floor(x+0.5) Generating Random Characters How do you generate random capital character? Solution: generate random number in range 65-90 57 60

The RandomCharacter Class Generalization We want to generate character from range ch1 to ch2 Remember: characters can be treated as integers (char)(ch1 + Math.random() * (ch2 ch1 + 1)) Design Diagram Enter full year (e.g., 2001): 2009 Enter month in number between 1 and 12: 2 February 2009 ----------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 RandomCharacter.java TestRandomCharacter.java 61 64 Stepwise Refinement The concept of method abstraction can be applied to the process of developing programs When writing a large program, you can use the divide and conquer strategy to decompose it into subproblems The subproblems can be further decomposed into smaller, more manageable problems Design Diagram readinput printcalendar (main) printmonthtitle getmonthname Enter full year (e.g., 2001): 2009 Enter month in number between 1 and 12: 2 February 2009 ----------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 printmonth printmonthbody getstartday gettotalnumofdays getnumofdaysinmonth isleapyear 62 65 PrintCalender Case Study Write a program that reads year and month and prints out a calendar. Enter full year (e.g., 2001): 2009 Enter month in number between 1 and 12: 2 February 2009 ----------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 PrintCalendar.java Design Diagram readinput printcalendar (main) printmonthtitle getmonthname Enter full year (e.g., 2001): 2009 Enter month in number between 1 and 12: 2 February 2009 ----------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 printmonth printmonthbody getstartday gettotalnumofdays getnumofdaysinmonth isleapyear 63 66

Design Diagram printcalendar (main) Enter full year (e.g., 2001): 2009 Enter month in number between 1 and 12: 2 February 2009 ----------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 readinput printmonth printmonthtitle getmonthname printmonthbody getstartday gettotalnumofdays getnumofdaysinmonth isleapyear 67 Design Diagram printcalendar (main) Enter full year (e.g., 2001): 2009 Enter month in number between 1 and 12: 2 February 2009 ----------------------------- Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 readinput printmonth printmonthtitle getmonthname printmonthbody getstartday How to get the start day for the first date in a month, assuming we know that Jan 1, 1800, was Wednesday? gettotalnumofdays getnumofdaysinmonth isleapyear 68 Implementation Top-down Implement one method in the structure chart at a time from the top to bottom Stubs can be used for the methods waiting to be implemented Bottom-up Implement one method in the structure chart at a time from the bottom to the top For each method implemented, write a test program to test it 69