CS110: PROGRAMMING LANGUAGE I

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

Chapter 5 Methods / Functions

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

Chapter 6 Methods. Dr. Hikmat Jaber

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, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

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

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

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

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

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

Lecture 5: Methods CS2301

Benefits of Methods. Chapter 5 Methods

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

Chapter 4 Mathematical Functions, Characters, and Strings

JAVA Programming Concepts

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

CS115 Principles of Computer Science

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

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

Lecture #6-7 Methods

Chapter 4. Mathematical Functions, Characters, and Strings

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

Module 4: Characters, Strings, and Mathematical Functions

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.

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

CS-201 Introduction to Programming with Java

CS-201 Introduction to Programming with Java

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

CS110D: PROGRAMMING LANGUAGE I

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

DUBLIN CITY UNIVERSITY

CS1150 Principles of Computer Science Methods

Chapter 4 Mathematical Functions, Characters, and Strings

AP CS Unit 3: Control Structures Notes

DUBLIN CITY UNIVERSITY

The Math Class. Using various math class methods. Formatting the values.

Methods. CSE 114, Computer Science 1 Stony Brook University

Expressions and operators

Object Oriented Methods : Deeper Look Lecture Three

Lecture 6: While Loops and the Math Class

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

JAVASCRIPT BASICS. JavaScript Math Functions. The Math functions helps you to perform mathematical tasks

Java, Arrays and Functions Recap. CSE260, Computer Science B: Honors Stony Brook University

Primitive Data Types: Intro

1.1 Your First Program

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

AP Computer Science A. Return values

Lecture 2:- Functions. Introduction

Introduction to Computer Science Unit 2. Notes

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

Recapitulate CSE160: Java basics, types, statements, arrays and methods

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

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

Introduction to Computer Science Unit 2. Notes

CS1150 Principles of Computer Science Methods

Advanced Object Concepts

1.1 Your First Program

CS171:Introduction to Computer Science II

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

Downloaded from Chapter 2. Functions

A Balanced Introduction to Computer Science, 3/E

A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN

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

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

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

A Foundation for Programming

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

Building Java Programs

Variable Manipulator Driver. Installation and Usage Guide. Revision: 1.0 Date: Monday, July 10, 2017 Authors: Alan Chow

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

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

Using Java Classes Fall 2018 Margaret Reid-Miller

Using Free Functions

Programmierpraktikum

1.1 Your First Program

Building Java Programs

Building Java Programs

M e t h o d s a n d P a r a m e t e r s

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

C Programs: Simple Statements and Expressions

Methods: A Deeper Look

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

Programming in C Quick Start! Biostatistics 615 Lecture 4

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

A human being should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts,

Building Java Programs

1.1 Your First Program

CS111: PROGRAMMING LANGUAGE II

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

Chapter 5: Methods. by Tony Gaddis. Starting Out with Java: From Control Structures through Objects. Fourth Edition

Methods CSC 121 Fall 2014 Howard Rosenthal

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Preview from Notesale.co.uk Page 2 of 79

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

1.1 Your First Program

Using API in Java. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Transcription:

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 Method Overloading The Math class

Introduction 3 Best way to develop and maintain a large program is to construct it from small, simple pieces, or modules. divide and conquer. Topics in this chapter static methods Declare a method with more than one parameter Method-call stack Simulation techniques with random-number generation. How to declare values that cannot change (i.e., constants) in your programs. Method overloading.

Program Modules in Java 4 Methods help you modularize a program by separating its tasks into self-contained units. Statements in method bodies Written only once Hidden from other methods Can be reused from several locations in a program Divide-and-conquer approach Constructing programs from small, simple pieces Software reusability Use existing methods as building blocks to create new pro-grams. Dividing a program into meaningful methods makes the program easier to debug and maintain.

Example 5 Find the sum of integers: from 1 to 10, from 20 to 30, and from 35 to 45,

Example (cont.) 6 int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to 10 is " + sum); sum = 0; for (int i = 20; i <= 30; i++) sum += i; System.out.println("Sum from 20 to 30 is " + sum); sum = 0; for (int i = 35; i <= 45; i++) sum += i; System.out.println("Sum from 35 to 45 is " + sum);

Example (cont.) 7 int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to 10 is " + sum); int sum = 0; for (int i = 20; i <= 30; i++) sum += i; System.out.println("Sum from 20 to 30 is " + sum); int sum = 0; for (int i = 35; i <= 45; i++) sum += i; System.out.println("Sum from 35 to 45 is " + sum);

Solution 8 public static int sum(int i1, int i2) { int sum = 0; for (int i = i1; i <= i2; i++) sum += i; return sum; } public static void main(string[] args) { System.out.println("Sum from 1 to 10 is " + sum(1, 10)); System.out.println("Sum from 20 to 30 is " + sum(20, 30)); System.out.println("Sum from 35 to 45 is " + sum(35, 45)); }

Defining Methods A method is a collection of statements that are grouped together to perform an operation. Define a method Invoke a method method header method body public static int max(int num1, int num2) { } modifier int result; return value type if (num1 > num2) result = num1; else result = num2; return result; method name return value formal parameters parameter list method signature int z = max(x, y); actual parameters (arguments) 9

animation Calling Methods, cont. pass the value of i pass the value of j public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); } System.out.println( "The maximum between " + i + " and " + j + " is " + k); public static int max(int num1, int num2) { int result; } if (num1 > num2) result = num1; else result = num2; return result; 10

Calling Methods, cont. 11

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. 12

Scope of Local Variables, cont. You can declare a local variable with the same name multiple times in different nonnesting blocks in a method, but you cannot declare a local variable twice in nested blocks. 13

Scope of Local Variables, cont. A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited in the loop body from its declaration and to the end of the block that contains the variable. The scope of i The scope of j public static void method1() {.. for (int i = 1; i < 10; i++) {.. int j;... } } 14

Scope of Local Variables, cont. It is fine to declare i in two non-nesting blocks public static void method1() { int x = 1; int y = 1; } for (int i = 1; i < 10; i++) { x += i; } for (int i = 1; i < 10; i++) { y += i; } It is wrong to declare i in two nesting blocks public static void method2() { } int i = 1; int sum = 0; for (int i = 1; i < 10; i++) sum += i; } 15

Scope of Local Variables, cont. 16

Passing Parameters 17 public static void nprintln(string message, int n) { for (int i = 0; i < n; i++) System.out.println(message); } Suppose you invoke the method using nprintln( Welcome to Java, 5); What is the output? Suppose you invoke the method using nprintln( Computer Science, 15); What is the output? Can you invoke the method using nprintln(15, Computer Science );

Method Overloading 18 Method overloading Methods of the same name declared in the same class Must have different sets of parameters Compiler selects the appropriate method to call by examining the number, types and order of the arguments in the call. Used to create several methods with the same name that perform the same or similar tasks, but on different types or different numbers of arguments. Literal integer values are treated as type int, so the method call in line 9 invokes the version of square that specifies an int parameter. Literal floating-point values are treated as type double, so the method call in line 10 invokes the version of square that specifies a double parameter.

19

20

Method Overloading (cont.) 21 Distinguishing Between Overloaded Methods The compiler distinguishes overloaded methods by their signatures the methods names and the number, types and order of their parameters. Return types of overloaded methods Method calls cannot be distinguished by return type. Figure 6.10 illustrates the errors generated when two methods have the same signature and different return types. Overloaded methods can have different return types if the methods have different parameter lists. Overloaded methods need not have the same number of parameters.

Method Overloading (cont.) 22

The Math Class Math fields for common mathematical constants Math.PI (3.141592653589793) Math.E (2.718281828459045) Class methods: Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods 23

Trigonometric Methods sin(double a) cos(double a) tan(double a) acos(double a) asin(double a) atan(double a) Radians toradians(90) 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 24

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. Examples: Math.exp(1) returns 2.71 Math.log(2.71) returns 1.0 Math.pow(2, 3) returns 8.0 Math.pow(3, 2) returns 9.0 Math.pow(3.5, 2.5) returns 22.91765 Math.sqrt(4) returns 2.0 Math.sqrt(10.5) returns 3.24 pow(double a, double b) Returns a raised to the power of b. sqrt(double a) Returns the square root of a. 25

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 rint(double x) x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double. int round(float x) Return (int)math.floor(x+0.5). long round(double x) Return (long)math.floor(x+0.5). 26

Rounding Methods Examples Math.ceil(2.1) returns 3.0 Math.ceil(2.0) returns 2.0 Math.ceil(-2.0) returns 2.0 Math.ceil(-2.1) returns -2.0 Math.floor(2.1) returns 2.0 Math.floor(2.0) returns 2.0 Math.floor(-2.0) returns 2.0 Math.floor(-2.1) returns -3.0 Math.rint(2.1) returns 2.0 Math.rint(2.0) returns 2.0 Math.rint(-2.0) returns 2.0 Math.rint(-2.1) returns -2.0 Math.rint(2.5) returns 2.0 Math.rint(-2.5) returns -2.0 Math.round(2.6f) returns 3 Math.round(2.0) returns 2 Math.round(-2.0f) returns -2 Math.round(-2.6) returns -3 27

min, max, and abs max(a, b)and min(a, b) Returns the maximum or minimum of two parameters. abs(a) Returns the absolute value of the parameter. random() Returns a random double value in the range [0.0, 1.0). Examples: Math.max(2, 3) returns 3 Math.max(2.5, 3) returns 3.0 Math.min(2.5, 3.6) returns 2.5 Math.abs(-2) returns 2 Math.abs(-2.1) returns 2.1 28

The random Method Generates a random double value greater than or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0). Examples: (int)(math.random() * 10) 50 + (int)(math.random() * 50) Returns a random integer between 0 and 9. Returns a random integer between 50 and 99. In general, a + Math.random() * b Returns a random number between a and a + b, excluding a + b. 29

30 That s all for today!! Text Book: Java : how to program, by P.J. Deitel, H.M. Deitel. -- 9th ed. Sections: 6.1, 6.2, 6.3, 6.4, 6.11, 6.12