cop3502 programming fundamentals for cis majors 1

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

Upload: meda

Post on 20-Feb-2016

45 views

Category:

Documents


0 download

DESCRIPTION

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi. Chapter 4 Loops for w hile do-while. Chapter 5 Methods Input arguments Output O verloading Code reusability Scope of variables. Methods. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: COP3502         Programming  Fundamentals for CIS Majors 1

COP3502 Programming Fundamentals for CIS Majors 1

Instructor: Parisa Rashidi

Page 2: COP3502         Programming  Fundamentals for CIS Majors 1

Chapter 4 Loops

forwhiledo-while

Last Week

Page 3: COP3502         Programming  Fundamentals for CIS Majors 1

Chapter 5 Methods

Input argumentsOutputOverloading

Code reusability Scope of variables

Objectives

Page 4: COP3502         Programming  Fundamentals for CIS Majors 1

Methods

Page 5: COP3502         Programming  Fundamentals for CIS Majors 1

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

Motivation

Page 6: COP3502         Programming  Fundamentals for CIS Majors 1

Obvious solution

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

Page 7: COP3502         Programming  Fundamentals for CIS Majors 1

What about some refactoring?

Refactor

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

x

x

x

y

y

y

x y

x y

x y

Page 8: COP3502         Programming  Fundamentals for CIS Majors 1

A better approach is to use a method

Solution

public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

modifier outputname

input

Methodbody

Page 9: COP3502         Programming  Fundamentals for CIS Majors 1

First, a method should be definedThen we can use the method

i.e. calling or invoking a method

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

Page 10: COP3502         Programming  Fundamentals for CIS Majors 1

When calling a method within the same class, we directly call the method

Invoking a 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

Page 11: COP3502         Programming  Fundamentals for CIS Majors 1

When calling a method from another class, use class name if a static method

Invoking a Method

public class TestClass{ public static void main(String[] args) { int total1 = AnotherClass .sum(1, 10); }

}Class name

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

}

Page 12: COP3502         Programming  Fundamentals for CIS Majors 1

When calling a method from another class, use class name if a static method

Invoking a Method

public class TestClass{ public static void main(String[] args) { AnotherClass a = new AnotherClass(); int total1 = a.sum(1, 10); }

} Instance name

public class AnotherClass{ public int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

}

Page 13: COP3502         Programming  Fundamentals for CIS Majors 1

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

So…

Page 14: COP3502         Programming  Fundamentals for CIS Majors 1

Method signature Combination of the method name and the

parameter list

Method Signature

public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

signature

Method header

Page 15: COP3502         Programming  Fundamentals for CIS Majors 1

Parameters

Parameters

public static int sum(int x, int y) { int sum = 0; for (int i = x; i <= y; i++) sum += i; return sum;}

Formal parameter

public static void main(String[] args) { int total1 = sum(1, 10);} Actual parameter

Page 16: COP3502         Programming  Fundamentals for CIS Majors 1

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.

Parameters

Page 17: COP3502         Programming  Fundamentals for CIS Majors 1

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

Output

Page 18: COP3502         Programming  Fundamentals for CIS Majors 1

A return statement is not required for a void method. return still can be used for terminating

the method This is not often done

Tip

Page 19: COP3502         Programming  Fundamentals for CIS Majors 1

Use “return” only once in a method! Easier to debug and trace

Programming Style

public int max(int x, int y) {  if (x > y) return x; else return y; }

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

Two exit points

Page 20: COP3502         Programming  Fundamentals for CIS Majors 1

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

Program

TestMax Run

Page 21: COP3502         Programming  Fundamentals for CIS Majors 1

Passing arguments

Program

public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

Page 22: COP3502         Programming  Fundamentals for CIS Majors 1

Program Trace

public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

i is now 5

Page 23: COP3502         Programming  Fundamentals for CIS Majors 1

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

j is now 2

Page 24: COP3502         Programming  Fundamentals for CIS Majors 1

Program Trace

public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

invoke method max(i,j)

Page 25: COP3502         Programming  Fundamentals for CIS Majors 1

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

Program Trace

public static void main(String[] args){ int i = 5; int j = 2; int k = max(i, j); }

pass the value of i to xpass the value of j to y

Page 26: COP3502         Programming  Fundamentals for CIS Majors 1

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

Declare variable result

Page 27: COP3502         Programming  Fundamentals for CIS Majors 1

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

(x > y) is true because (5 > 2)

Page 28: COP3502         Programming  Fundamentals for CIS Majors 1

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

result is now 5

Page 29: COP3502         Programming  Fundamentals for CIS Majors 1

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

return result which is 5

Page 30: COP3502         Programming  Fundamentals for CIS Majors 1

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

return max(i, j) and assign the return value to k

Page 31: COP3502         Programming  Fundamentals for CIS Majors 1

Program Trace

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

finished

Page 32: COP3502         Programming  Fundamentals for CIS Majors 1

Methods reduce redundant coding and enable code reuse.

Methods modularize code and improve the quality of the program.

Modularizing Code

PrimeNumberMethod

Run

Page 33: COP3502         Programming  Fundamentals for CIS Majors 1

Chapter 5 Methods

Input arguments Output

Previously

Page 34: COP3502         Programming  Fundamentals for CIS Majors 1

Methods Overload …

Memory management

Today

Page 35: COP3502         Programming  Fundamentals for CIS Majors 1

Write a method that converts a decimal integer to a hexadecimal.

Program

Decimal2HexConversion Run

Page 36: COP3502         Programming  Fundamentals for CIS Majors 1

Converting a decimal number x (e.g. 74) into a hexadecimal number (e.g. 4A) 1. Divide x by 162. Save remainder and quotient3. Repeat step 1 and 2 until quotient is 04. Form the hexadecimal number from remainders

(the most recent remainder will be the leftmost digit)

Program Explained

Page 37: COP3502         Programming  Fundamentals for CIS Majors 1

Memory & Methods

Page 38: COP3502         Programming  Fundamentals for CIS Majors 1

A data structure Last in, first out (LIFO) Two basic operation

Pop Push

Stack

xYZ

Push Pop

Page 39: COP3502         Programming  Fundamentals for CIS Majors 1

How memory is arranged1. 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

Memory

Page 40: COP3502         Programming  Fundamentals for CIS Majors 1

Revisiting Program

Public static int max(int x, int y) { int result= 0; if(x > y) result = x; else result = y; return result;}

public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); }

Each time a method is called, the system stores parameters and variables in stack memory.

Page 41: COP3502         Programming  Fundamentals for CIS Majors 1

How memory is managed?

Memory

Space required for

main method:

k:i:5j:2

Space required for

main method:

k:i:5j:2

Space required for

main method:

k:i:5j:2

Space required for

main method:

k: 5i:5j:2

Stackis empty

Space required for

maxmethod:

x:5y:2

Space required for

maxmethod:

Result: 5x:5y:2

Page 42: COP3502         Programming  Fundamentals for CIS Majors 1

What about reference types? E.g. Random r = new Random();

Pass by Reference

Space required for main method:

r(reference)

Stack Memory Heap Memory

Actual Object

Page 43: COP3502         Programming  Fundamentals for CIS Majors 1

What about reference types? E.g. Random r = new Random();

Pass by Reference

Space required for main method:

r(reference)

Stack Memory Heap Memory

Actual Object

Space required for

testmethod:

x

Page 44: COP3502         Programming  Fundamentals for CIS Majors 1

If primitive types are passed Value is passed Changes inside method will not affect the

variable outside the method If a reference type is passed

Reference is passed (address of memory location containing actual object)

Changes inside the method will affect the variable

Passing Arguments

Page 45: COP3502         Programming  Fundamentals for CIS Majors 1

Method Overload

Page 46: COP3502         Programming  Fundamentals for CIS Majors 1

Different versions of the same method accepting different arguments

Method Overload

TestMethodOverloading Run

Page 47: COP3502         Programming  Fundamentals for CIS Majors 1

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

Tip

Page 48: COP3502         Programming  Fundamentals for CIS Majors 1

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.

Method Overload

Page 49: COP3502         Programming  Fundamentals for CIS Majors 1

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

Page 50: COP3502         Programming  Fundamentals for CIS Majors 1

Variable Scope

Page 51: COP3502         Programming  Fundamentals for CIS Majors 1

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

Page 52: COP3502         Programming  Fundamentals for CIS Majors 1

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.

Variable Scope

public static void method1() { . . for (int i = 1; i < 10; i++) { . . int j; . . . } }

The scope of j

The scope of i

Page 53: COP3502         Programming  Fundamentals for CIS Majors 1

You can declare a local variable with the same name multiple times in different non-nesting blocks in a method

You cannot declare a local variable twice in nested blocks.

Variable Scope

Page 54: COP3502         Programming  Fundamentals for CIS Majors 1

A variable declared in a method

Variable Scope

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 fine to declare i in two non-nesting blocks public static void method2() {

int i = 1; int sum = 0;

for (int i = 1; i < 10; i++) {

sum += i; } }

It is wrong to declare i in two nesting blocks

Page 55: COP3502         Programming  Fundamentals for CIS Majors 1

Method Abstraction

Page 56: COP3502         Programming  Fundamentals for CIS Majors 1

You can think of the method body as a black box that contains the detailed implementation for the method.

Abstraction

Method Header

Method body Black Box

Optional arguments for Input

Optional return value

Page 57: COP3502         Programming  Fundamentals for CIS Majors 1

Write a method once and reuse it anywhere.

Hide the implementation from the user. Change it without affecting the user

Reduce complexity.

Method Benefits

Page 58: COP3502         Programming  Fundamentals for CIS Majors 1

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

Method Benefits

Page 59: COP3502         Programming  Fundamentals for CIS Majors 1

HW4 due todayHW5 postedMonday: homework review session

Agenda

Page 60: COP3502         Programming  Fundamentals for CIS Majors 1

Chapter 5 Code reusability & program design

Objectives

Page 61: COP3502         Programming  Fundamentals for CIS Majors 1

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.

Stepwise Refinement

Main Task

Task 1

Task 1-1

Task 1-2

Task 2

Task 3

Page 62: COP3502         Programming  Fundamentals for CIS Majors 1

An example to demonstrate the stepwise refinement approach:

Stepwise Refinement

PrintCalendar Run

Page 63: COP3502         Programming  Fundamentals for CIS Majors 1

Stepwise Refinement

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Page 64: COP3502         Programming  Fundamentals for CIS Majors 1

Stepwise Refinement

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Page 65: COP3502         Programming  Fundamentals for CIS Majors 1

Stepwise Refinement

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Page 66: COP3502         Programming  Fundamentals for CIS Majors 1

Stepwise Refinement

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Page 67: COP3502         Programming  Fundamentals for CIS Majors 1

Stepwise Refinement

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Page 68: COP3502         Programming  Fundamentals for CIS Majors 1

Stepwise Refinement

printCalendar (main)

readInput printMonth

getStartDay

printMonthTitle printMonthBody

getTotalNumOfDays

getNumOfDaysInMonth

getMonthName

isLeapYear

Page 69: COP3502         Programming  Fundamentals for CIS Majors 1

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.

Top Down Design

A Skeleton for printCalendar

Page 70: COP3502         Programming  Fundamentals for CIS Majors 1

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.

Bottom Up Design

Page 71: COP3502         Programming  Fundamentals for CIS Majors 1

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.

Comparison

Page 72: COP3502         Programming  Fundamentals for CIS Majors 1

An example to demonstrate the stepwise refinement approach:

Program Revisited

PrintCalendar Run

Page 73: COP3502         Programming  Fundamentals for CIS Majors 1

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

Page 74: COP3502         Programming  Fundamentals for CIS Majors 1

Random character generator

Program

TestRandomCharacter

Run

RandomCharacter

Page 75: COP3502         Programming  Fundamentals for CIS Majors 1

Math Class

Page 76: COP3502         Programming  Fundamentals for CIS Majors 1

Class constants: PI E

Class methods: Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods

Math Class

Page 77: COP3502         Programming  Fundamentals for CIS Majors 1

Trigonometric methods sin(double a) cos(double a) tan(double a) acos(double a) asin(double a) atan(double a)

Math Class

Examples:

Math.sin(0) returns 0.0 Math.sin(Math.PI / 6) returns

0.5 Math.sin(Math.PI / 2) returns

1.0Math.cos(0) returns 1.0Math.cos(Math.PI / 6)

returns 0.866 Math.cos(Math.PI / 2)

returns 0

Page 78: COP3502         Programming  Fundamentals for CIS Majors 1

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

Page 79: COP3502         Programming  Fundamentals for CIS Majors 1

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

Math Class

Page 80: COP3502         Programming  Fundamentals for CIS Majors 1

Rounding examplesMath.ceil(2.1) returns 3.0 Math.ceil(2.0) returns 2.0Math.ceil(-2.0) returns –2.0Math.ceil(-2.1) returns -2.0Math.floor(2.1) returns 2.0Math.floor(2.0) returns 2.0Math.floor(-2.0) returns –2.0Math.floor(-2.1) returns -3.0Math.rint(2.1) returns 2.0Math.rint(2.0) returns 2.0Math.rint(-2.0) returns –2.0Math.rint(-2.1) returns -2.0Math.rint(2.5) returns 2.0Math.rint(-2.5) returns -2.0Math.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

Page 81: COP3502         Programming  Fundamentals for CIS Majors 1

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 valuein the range [0.0, 1.0).

Math Class

Page 82: COP3502         Programming  Fundamentals for CIS Majors 1

random method Generates a random double value greater than

or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0).

Math Class

(int)(Math.random() * 10) Returns a random integer

between 0 and 9.

50 + (int)(Math.random() * 50) Returns a random integer between 50 and 99.

a + Math.random() * b Returns a random number between

a and a + b, excluding a + b.