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

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

Chapter 5 Methods / Functions

Chapter 6 Methods. Dr. Hikmat Jaber

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

CS110: PROGRAMMING LANGUAGE I

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

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

Benefits of Methods. Chapter 5 Methods

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

JAVA Programming Concepts

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 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

CS115 Principles of Computer Science

Lecture 5: Methods CS2301

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

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

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

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

Chapter 4 Mathematical Functions, Characters, and Strings

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

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.

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

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);

Chapter 4. Mathematical Functions, Characters, and Strings

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

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

CS-201 Introduction to Programming with Java

CS-201 Introduction to Programming with Java

Expressions and operators

CS1150 Principles of Computer Science Methods

Module 4: Characters, Strings, and Mathematical Functions

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

CS1150 Principles of Computer Science Methods

Primitive Data Types: Intro

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

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

Using Free Functions

CS110D: PROGRAMMING LANGUAGE I

DUBLIN CITY UNIVERSITY

DUBLIN CITY UNIVERSITY

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

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

Object Oriented Methods : Deeper Look Lecture Three

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

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

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

Introduction to programming using Python

Methods CSC 121 Fall 2016 Howard Rosenthal

Functions. Lecture 6 COP 3014 Spring February 11, 2018

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

Methods CSC 121 Spring 2017 Howard Rosenthal

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

Chapter 4 Mathematical Functions, Characters, and Strings

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

Functions. Systems Programming Concepts

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

C Programs: Simple Statements and Expressions

Methods: A Deeper Look

Lecture 2:- Functions. Introduction

Methods CSC 121 Fall 2014 Howard Rosenthal

A Foundation for Programming

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

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

1.1 Your First Program

Programming in C Quick Start! Biostatistics 615 Lecture 4

The return Statement

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

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Programmierpraktikum

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

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

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Lecture 04 FUNCTIONS AND ARRAYS

1.1 Your First Program

Introduction to Programming (Java) 4/12

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Topic 12 more if/else, cumulative algorithms, printf

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

C Functions. 5.2 Program Modules in C

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

Chapter 7 User-Defined Methods. Chapter Objectives

User Defined Functions

Downloaded from Chapter 2. Functions

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

Variables, Types, Operations on Numbers

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

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)

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

CS171:Introduction to Computer Science II

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

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

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

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

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

Transcription:

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 variables Objectives

Methods

Motivation Suppose we want to write a program to find the sum of integers from 1 to 10 from 20 to 30 from 35 to 45

Naïve Solution Obvious solution 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);

Refactor What about some refactoring? int sum = 0; for (int i = x 1 ; i <= 10; y i++) sum += i; System.out.println("Sum from x 1 to 10 y is " + sum); sum = 0; for (int i = 20; x i <= 30; y i++) sum += i; System.out.println("Sum from 20 x to 30 y is " + sum); sum = 0; for (int i = 35; x i <= 45; y i++) sum += i; System.out.println("Sum from 35 x to 45 y is " + sum);

Solution A better approach is to use a method modifier output name input Method body public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;

Invoking a Method First, a method should be defined Then we can use the method i.e. calling or invoking a method public static void main(string[] args) { int total1 = sum(1, 10); int total2= sum(20, 30); int total3 = sum(35, 45); int total4 = sum(35,1000);

Invoking a Method When calling a method within the same class, we directly call the method public class TestClass{ public static void main(string[] args) { int total1 = sum(1, 10); //---------------------------------------------- public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum; calling directly

Invoking a Method When calling a method from another class, use class name if a static method public class AnotherClass{ public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum; public class TestClass{ public static void main(string[] args) { int total1 = AnotherClass.sum(1, 10); Class name

Invoking a Method When calling a method from another class, use class name if a static method public class AnotherClass{ public int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum; public class TestClass{ public static void main(string[] args) { AnotherClass a = new AnotherClass(); int total1 = a.sum(1, 10); Instance name

So Method is A collection of statements grouped together to perform an operation To use a method We invoke the method E.g. int result = sum(1,10);

Method Signature Method signature Combination of the method name and the parameter list Method header signature public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;

Parameters Parameters Formal parameter public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum; public static void main(string[] args) { int total1 = sum(1, 10); Actual parameter

Parameters Formal parameters: Variables defined in the method header Actual parameters: When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.

Output If the method does not return a value, the return type is the keyword void. It means nothing will be returned A method may return a value: Use return keyword to return the value E.g. return sum; return keyword is required if return type is anything other than void

Tip A return statement is not required for a void method. return still can be used for terminating the method This is not often done

Programming Style Use return only once in a method! Easier to debug and trace public int max(int x, int y) { if (x > y) return x; else return y; Two exit points public int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result; One exit point: This is better

Program This program demonstrates calling a method max to return the largest value among a set of values. TestMax Run

Program Passing arguments public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;

Program Trace i is now 5 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;

Program Trace j is now 2 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;

Program Trace invoke method max(i,j) public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;

Program Trace pass the value of i to x pass the value of j to y public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;

Program Trace Declare variable result public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;

Program Trace (x > y) is true because (5 > 2) public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;

Program Trace result is now 5 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;

Program Trace return result which is 5 public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;

Program Trace return max(i, j) and assign the return value to k public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;

Program Trace finished public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;

Modularizing Code Methods reduce redundant coding and enable code reuse. Methods modularize code and improve the quality of the program. PrimeNumberMethod Run

Previously Chapter 5 Methods Input arguments Output

Today Methods Overload Memory management

Program Write a method that converts a decimal integer to a hexadecimal. Decimal2HexConversion Run

Program Explained Converting a decimal number x (e.g. 74) into a hexadecimal number (e.g. 4A) 1. Divide x by 16 2. Save remainder and quotient 3. Repeat step 1 and 2 until quotient is 0 4. Form the hexadecimal number from remainders (the most recent remainder will be the leftmost digit)

Memory & Methods

Stack A data structure Last in, first out (LIFO) Two basic operation Pop Push Push Pop Z Y x

Memory How memory is arranged 1. Registers Inside the processor, very limited, you have no direct access 2. RAM Stack memory Inside RAM, very fast, lifetime of objects should be known, all primitive variables placed here Heap memory Inside RAM, reference values placed here 3. Constant values Will be directly replaced in code

Revisiting Program Each time a method is called, the system stores parameters and variables in stack memory. Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; public static void main(string[] args) { int i = 5; int j = 2; int k = max(i, j); return result;

Memory How memory is managed? Space required for max method: x:5 y:2 Space required for max method: Result: 5 x:5 y:2 Space required for main method: k: i:5 j:2 Space required for main method: k: i:5 j:2 Space required for main method: k: i:5 j:2 Space required for main method: k: 5 i:5 j:2 Stack is empty

Pass by Reference What about reference types? E.g. Random r = new Random(); Actual Object Space required for main method: r (reference) Stack Memory Heap Memory

Pass by Reference What about reference types? E.g. Random r = new Random(); Space required for test method: x Space required for main method: r (reference) Stack Memory Actual Object Heap Memory

Passing Arguments If primitive types are passed Value is passed Changes inside method will not affect the variable If a reference type is passed Reference is passed (address of memory location containing actual object) Changes inside the method will affect the variable

Method Overload

Method Overload Different versions of the same method accepting different arguments TestMethodOverloading Run

Tip Method overload is only based on input arguments Method overload can not be based on different output values Method overload cannot be based on different modifiers

Method Overload Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error.

Ambiguous invocation public class AmbiguousOverloading { public static void main(string[] args) { System.out.println(max(1, 2)); public static double max(int num1, double num2) { double result = 0; if (num1 > num2) result = num1; else result = num2; return result; public static double max(double num1, int num2) { double result = 0; if (num1 > num2) result = num1; else result = num2; return result;

Variable Scope

Variable Scope Scope: Part of the program where the variable can be referenced. A local variable: A variable defined inside a method. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable.

Variable Scope A variable declared in the initial action part of a for loop has its scope in the entire loop. 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. The scope of i The scope of j public static void method1() {.. for (int i = 1; i < 10; i++) {.. int j;...

Variable Scope You can declare a local variable with the same name multiple times in different nonnesting blocks in a method You cannot declare a local variable twice in nested blocks.

Variable Scope A variable declared in a method 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;

Method Abstraction

Abstraction You can think of the method body as a black box that contains the detailed implementation for the method. Optional arguments for Input Optional return value Method Header Method body Black Box

Method Benefits Write a method once and reuse it anywhere. Hide the implementation from the user. Change it without affecting the user Reduce complexity.

Method Benefits Example Math class provides many methods Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods

Stepwise Refinement When writing a large program, you can use the divide and conquer strategy, also known as stepwise refinement, to decompose it into sub-problems. The sub-problems can be further decomposed into smaller, more manageable problems. Main Task Task 1 Task 2 Task 1-1 Task 1-2 Task 3

Stepwise Refinement An example to demonstrate the stepwise refinement approach: PrintCalendar Run

Stepwise Refinement printcalendar (main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday gettotalnumofdays getnumofdaysinmonth isleapyear

Stepwise Refinement printcalendar (main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday gettotalnumofdays getnumofdaysinmonth isleapyear

Stepwise Refinement printcalendar (main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday gettotalnumofdays getnumofdaysinmonth isleapyear

Stepwise Refinement printcalendar (main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday gettotalnumofdays getnumofdaysinmonth isleapyear

Stepwise Refinement printcalendar (main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday gettotalnumofdays getnumofdaysinmonth isleapyear

Stepwise Refinement printcalendar (main) readinput printmonth printmonthtitle printmonthbody getmonthname getstartday gettotalnumofdays getnumofdaysinmonth isleapyear

Top Down Design Top-down approach is to implement one method in the structure chart at a time from the top to the bottom. Implement the main method first and then use a stub for each one of the methods. Stubs can be used for the methods waiting to be implemented. A stub is a simple but incomplete version of a method. The use of stubs enables you to test invoking the method from a caller. A Skeleton for printcalendar

Bottom Up Design Bottom-up approach is to 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.

Comparison Both top-down and bottom-up methods are fine. Both approaches implement the methods incrementally and help to isolate programming errors and makes debugging easy. Sometimes, they can be used together.

Program Revisited An example to demonstrate the stepwise refinement approach: PrintCalendar Run

Program As introduced before, each character has a unique Unicode between 0 and FFFF in hexadecimal (65535 in decimal). To generate a random character is to generate a random integer between 0 and 65535. The Unicode for lowercase letters are consecutive integers starting from the Unicode for 'a', then for 'b', 'c',..., and 'z'. A random character between any two characters ch1 and ch2 with ch1 < ch2 can be generated as follows: Random r = new Random(); char x = ch1 + r.nextint(ch2 ch1 + 1)

Program Random character generator RandomCharacter TestRandomCharacter Run

Math Class

Math Class Class constants: PI E Class methods: Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods

Math Class Trigonometric methods sin(double a) cos(double a) tan(double a) acos(double a) asin(double a) atan(double a) 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 Radians

Math Class 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.

Math Class 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).

Rounding 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 Math Class

Math Class Min, max, etc 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).

Math Class random method Generates a random double value greater than or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0). (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. a + Math.random() * b Returns a random number between a and a + b, excluding a + b.